如何在AngularJS中修复此错误

时间:2014-07-26 12:05:30

标签: angularjs angularjs-directive

如何解决此错误?

TypeError: object is not a function
    at http://localhost:9000/app/topItems/topItems.directive.js:30:11
    at Scope.$broadcast (http://localhost:9000/bower_components/angular/angular.js:12887:28)
    at Scope.$destroy (http://localhost:9000/bower_components/angular/angular.js:12545:14)
    at Scope.$delegate.__proto__.$destroy (<anonymous>:812:29)
    at cleanupLastView (http://localhost:9000/bower_components/angular-ui-router/release/angular-ui-router.js:2712:26)
    at http://localhost:9000/bower_components/angular-ui-router/release/angular-ui-router.js:2739:13
    at publicLinkFn (http://localhost:9000/bower_components/angular/angular.js:5933:29)
    at updateView (http://localhost:9000/bower_components/angular-ui-router/release/angular-ui-router.js:2733:23)
    at http://localhost:9000/bower_components/angular-ui-router/release/angular-ui-router.js:2697:11
    at Scope.$broadcast (http://localhost:9000/bower_components/angular/angular.js:12887:28) angular.js:9997

以下是错误指令:

.directive('topItems', ['$window', function($window) {
    var linkFn;
    linkFn = function(scope,element,atts) {
      function setHeight() {
        var winHeight = $(window).height();
        var headerHeight = 72;
        var topItemHeight = winHeight - headerHeight + 'px';
        element.css('height', topItemHeight);

        if(winHeight < 480)
          scope.limit = 6; // 
        else if(winHeight > 480 && winHeight < 600)
            scope.limit = 9;
        else if(winHeight > 600 && winHeight < 850)
            scope.limit = 12;
        else if(winHeight > 850)
            scope.limit = 18;

        // console.log(winHeight, headerHeight, topItemHeight, scope.limit);
      }

      setHeight();

      var windowListenerDeregistraion = $(window).on('resize', setHeight);

      // I think the problem is to do with the $destroy
      scope.$on('$destroy', function(){
          windowListenerDeregistraion();
      });
    }
    return {
      restrict: 'E', // Restrict to E(Element), A(Attribute)
      // scope: {
      //   limit: '@'
      // },
      templateUrl: 'app/topItems/topItems.html',
      link: linkFn
    }
  }]);

1 个答案:

答案 0 :(得分:1)

windowListenerDeregistraion是一个jQuery对象,而不是一个函数。

您在公开$(window).on('resize', setHeight);时已经将处理程序绑定到窗口调整大小事件。

你不应该再做一次,虽然不清楚你的期望是什么。