[英]How to call a directive's function from the controller on Angular
我有一个控制个性化多选的指令。 有时我想从主控制器中清除所有多选。 我具有填充“双向filter
”双向变量的multiselect值,并且能够从其中删除内容,但是这样做时,我还必须更改某些样式和其他内容。 换句话说:我必须从属于控制器的按钮调用属于指令的方法。 使用这种数据结构甚至可能吗?
(顺便说一句,我发现了其他问题和示例,但它们的指令没有自己的范围。)
function MultiselectDirective($http, $sce) {
return {
restrict: 'E',
replace: true,
templateUrl: 'temp.html',
scope: {
filter: "=",
name: "@",
url: "@"
},
link: function(scope, element, attrs){
//do stuff
scope.function_i_need_to_call = function(){
//updates directtive template styles
}
}
}
}
最佳解决方案和角度使用event
。
jsfiddle上的实时示例。
angular.module('ExampleApp', []) .controller('ExampleOneController', function($scope) { $scope.raise = function(val){ $scope.$broadcast('raise.event',val); }; }) .controller('ExampleTwoController', function($scope) { $scope.raise = function(val){ $scope.$broadcast('raise.event',val); }; }) .directive('simple', function() { return { restrict: 'A', scope: { }, link: function(scope) { scope.$on('raise.event',function(event,val){ console.log('i`m from '+val); }); } } });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-app="ExampleApp"> <div ng-controller="ExampleOneController"> <h3> ExampleOneController </h3> <form name="ExampleForm" id="ExampleForm"> <button ng-click="raise(1)" simple> Raise 1 </button> </form> </div> <div ng-controller="ExampleTwoController"> <h3> ExampleTwoController </h3> <form name="ExampleForm" id="ExampleForm"> <button ng-click="raise(2)" simple> Raise 2 </button> </form> </div> </body>
我认为从控制器链接到指令的更好解决方案是:
// in directive
return {
scope: {
controller: "=",
},
controller: function($scope){
$scope.mode = $scope.controller.mode;
$scope.controller.function_i_need_to_call = function(){}
$scope.controller.currentState = state;
}
}
// in controller
function testCtrl($scope){
// config directive
$scope.multiselectDirectiveController = {
mode: 'test',
};
// call directive methods
$scope.multiselectDirectiveController.function_i_need_to_call();
// get directive property
$scope.multiselectDirectiveController.currentState;
}
// in template
<Multiselect-directive controller="multiselectDirectiveController"></Multiselect-directive>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.