简体   繁体   English

模型更改后,事件未绑定到指令-AngularJS

[英]Event not binding to directive after model change - AngularJS

In my angularjs app, I have an element directive on which I bind an event listener that listens to a controller broadcast event. 在我的angularjs应用中,我有一个element指令,在该指令上我绑定了一个监听控制器广播事件的事件监听器。

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

This directive is rendered multiple times in my view using the ng-repeat directive with an array. 在我的视图中,此伪指令使用ng-repeat伪指令与数组多次渲染。

Whenever I load the view and the event is fired, all listeners are called accordingly, but when I add a new item in the array, which causes another directive to be rendered, its listener is never called. 每当我加载视图并触发事件时,都会相应地调用所有侦听器,但是当我在数组中添加新项(导致呈现另一条指令)时,就不会调用其侦听器。 Is there a way to force it to bind? 有没有办法强迫它绑定?

You have to shoot for event listener 您必须拍摄事件监听器

$scope.$emit('controllerEvent', {}); $ scope。$ emit('controllerEvent',{});

Whenever it is changed 每当改变

After a lot of fiddling, I found a way around it. 经过很多摆弄后,我找到了解决方法。

Since I was binding it to the local scope of the directive, it was possibly losing reference to it when adding more data. 由于我将其绑定到指令的本地范围,因此在添加更多数据时可能会丢失对它的引用。 To fix it, I simply changed the binding to the $rootScope (had to inject it in the directive); 为了解决这个问题,我仅更改了对$ 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'
    }
}]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM