【问题标题】:AngularJS directive DOM manipulation not executing link()AngularJS指令DOM操作不执行链接()
【发布时间】:2015-01-07 14:58:01
【问题描述】:

试图做一些 DOM 操作,但 link() 从未被调用,所以没有任何反应:

app.js

var app = angular.module('app', ['directives', ...]);
var directives = angular.module('directives', []);
...

directives.js

directives.directive('doIt', ['$window', function($window) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            console.log('Inside link()');
            // Do stuff with $window
        }
    };
]});

HTML

<html ng-app="app">
    <body>
        <div ng-view>
            <div do-it>
                // ....
            </div>
        </div>
    </body>
</html>

我错过了什么?

【问题讨论】:

    标签: javascript angularjs angularjs-directive dom-manipulation


    【解决方案1】:

    你的方括号不正确

    directives.directive('doIt', ['$window', function($window) {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                console.log('Inside link()');
                // Do stuff with $window
            }
        };
    
        }]);//Check this part. The square bracket was on the wrong side of }
    

    像我在上面一样移动它

    你的模块声明中还有一些额外的时间段

    var app = angular.module('app', ['directives']); //去掉多余的....的

    【讨论】:

    • 啊哈,我发现了问题...我忘了在我的index.html 中包含directives.js。哦!
    【解决方案2】:

    这是 plnkr 的帮助吗?plnkr

     angular.module('app', [])
    // .controller('Controller', ['$scope', function($scope) {
    //   $scope.customer = {
    //     name: 'Naomi',
    //     address: '1600 Amphitheatre'
    //   };
    // }])
    .directive('doIt', ['$window', function($window) {
      return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            console.log('Inside link()');
            // Do stuff with $window
        }
      };
    }]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-23
      • 1970-01-01
      • 1970-01-01
      • 2016-01-03
      • 1970-01-01
      • 2016-08-09
      • 2017-10-30
      • 1970-01-01
      相关资源
      最近更新 更多