9

基本的には、angular が DOM を操作した後に要素の幅を測定したいと考えています。そのために $timeout を使用したいのですが、エラーが発生し続けます。

HTML

   <div ng-app="github">
      <ul mynav>
        <li ng-repeat="nav in navItems">{{nav.name}}</li>
      </ul>

      </div>
    </div>

CSS

ul,li {
  display:inline-block;
}
li {
  margin-right:1em;
}

JS

(function() {
  angular.module('github', [])
    .directive('mynav', function($window) {
      return {
        restrict: 'A',
        link: function(scope, element, attrs, timeout) {
          scope.navItems = [{
            "name": "home"
          }, {
            "name": "link1"
          }, {
            "name": "link2"
          }, {
            "name": "link3"
          }];
          timeout(function() {
            console.log($(element).width());
          })
        }

      }
    });
})();
4

3 に答える 3

14

link関数は、依存関係を挿入する正しい場所ではありません。以下に示すように、パラメーターのシーケンスを定義しています。そこに依存関係を置くことはできません。

link(scope, element, attrs, controller, transcludeFn) {

ディレクティブ$timeoutに依存関係を挿入しfunctionます。

(function() {
  angular.module('github', [])
    .directive('mynav', function($window, $timeout) { //<-- dependency injected here
      return {

次に、注入された$timeout内部link関数を使用するだけです

$timeout(function() {
    console.log(element.width());
})
于 2016-08-26T10:39:23.863 に答える
-2

以下のように、timeout を setinterval に置き換えるだけです。

(function() {
  angular.module('github', [])
    .directive('mynav', function($window) {
      return {
        restrict: 'A',
        link: function(scope, element, attrs, timeout) {
          scope.navItems = [{
            "name": "home"
          }, {
            "name": "link1"
          }, {
            "name": "link2"
          }, {
            "name": "link3"
          }];
          setInterval(function() { // replpace 'timeout' with 'setInterval'
            console.log($(element).width());
          })
        }

      }
    });
})();

それがうまくいくことを願っています。

于 2016-08-26T10:41:12.093 に答える