2017-08-25 87 views
0

在我的angularjs應用程序中,我有一個元素指令,在該指令上綁定偵聽控制器廣播事件的事件偵聽器。事件在模型更改後沒有綁定到指令 - AngularJS

app.directive('listItem', function(){ 
    return { 
    link: function(scope, element){ 
     scope.$on('controllerEvent', function(e,attr) { 
      console.log('event fired!') 
     }); 
    }, 
    templateUrl:'views/fragments/list.html' 
    } 
}]); 

該指令在我的視圖中使用帶數組的ng-repeat指令呈現多次。

每當我加載視圖並觸發事件時,所有偵聽器都會相應地調用,但是當我在數組中添加一個新項目時,會導致另一個指令被渲染,其偵聽器將永遠不會被調用。有沒有辦法強制它綁定?

回答

0

你要拍的事件監聽器

$範圍$發出( 'controllerEvent',{})。

每當改變

+0

我不明白這會如何有用,你說我應該向控制器發出一個事件向上?爲什麼? – arvere

0

很多擺弄之後,我發現它周圍的方式。

因爲我將它綁定到指令的局部範圍,所以在添加更多數據時可能會失去對它的引用。 爲了解決這個問題,我簡單地將綁定改爲$ rootScope(必須將其注入到指令中);

app.directive('listItem', ['$rootScope', function($rootScope){ 
    return { 
     link: function(scope, element){ 
      $rootScope.$on('controllerEvent', function(e,attr) { 
       console.log('event fired!') 
      }); 
     }, 
     templateUrl:'views/fragments/list.html' 
    } 
}]);