我在一个容器中有几个指令,在其中我需要能够专门删除每个指令。每个指令位于一个大div中,该div也包含一个remove按钮。
控制器:
app.controller('eventController', function($scope, $rootScope){;
$scope.removeEvent = function (id){
console.log(id);
$scope.$broadcast("$destroy" + id);
}
});
指令:
app.directive('eventView', function () {
return {
restrict: 'E',
replace:true,
templateUrl: 'partials/EventView.html',
controller: 'eventController',
scope: {id : '@'},
link: function(scope, element){
scope.$on("$destroy"+scope.id,function() {
element.remove();
});
}
}
});
问题是我在此行出现错误,scope.$on("$destroy"+scope.id,function() {
说id未定义
添加指令:
app.controller('AddTimelineController', function($scope, $rootScope,$compile){
$scope.id = 0;
$scope.addEvent = function (){
newElement = $compile("<event-View id=\"{{id}}\"></event-View>")($scope);
$scope.id = $scope.id+1;
eventContainer = angular.element(document.getElementById('eventContainer'));
eventContainer.append(newElement);
}
});
删除指令:
app.controller('eventController', function($scope, $rootScope){;
$scope.removeEvent = function (id){
console.log(id);
$scope.$broadcast("$destroy" + id);
}
});
而不是使用$broadcast
我会使用$watch
到link
,将监听id
的变化。
观看演示 Plunker
的确,$watch()
vs进行污垢检查$broadcast()
并且$broadcast()
比便宜$watch()
。
但是,在您的情况下,您调用了link
before removeEvent
,因此指令不能正确id
使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句