Angularjs 从指令调用方法到控制器
我想从指令调用控制器中的函数Angularjs 从指令调用方法到控制器,angularjs,Angularjs,我想从指令调用控制器中的函数 .directive('multEcs', ['$http', function($http){ return{ restrict: 'A', replace:false, scope : { myFunctionToCall : '=' }, link: function(scope, elem, attr){
.directive('multEcs', ['$http', function($http){
return{
restrict: 'A',
replace:false,
scope : {
myFunctionToCall : '='
},
link: function(scope, elem, attr){
scope.myFunctionToCall();
}
}
}]);
我的指令
.directive('multEcs', ['$http', function($http){
return{
restrict: 'A',
replace:false,
link: function(scope, elem, attr){
scope.addToArray();
}
}
}]);
控制器中的方法
$scope.addToArray = function(){
console.log('method called');
}
尝试将要调用的函数传递给指令
.directive('multEcs', ['$http', function($http){
return{
restrict: 'A',
replace:false,
scope : {
myFunctionToCall : '='
},
link: function(scope, elem, attr){
scope.myFunctionToCall();
}
}
}]);
第一种方式是控制器和指令之间的单向绑定: JS: HTML: HTML:
因为您没有使用隔离作用域。。这应该按原样工作。你试过了吗?你有什么问题吗?如果是,请提供详细信息无错误,但未调用函数。控制器用于路由上设置的整个页面。指令在页面内。这有什么问题吗?你能安装plunker吗[我刚刚添加了js文件,请看一看。我的代码有效,但仅当该方法从指令内的另一个方法调用时有效。我的代码有效,但仅当该方法从指令内的另一个方法调用时有效。我的代码有效,但仅当该方法从指令内的另一个方法调用时有效。
<div ng-app="App">
<div ng-controller="HomeCtrl">
<div mult-ecs add-to-array="addToArray()">multEcs</div>
</div>
</div>
angular.module('App',[])
.directive('multEcs', [function(){
return {
restrict: 'A',
replace: false,
controller: 'HomeCtrl',
scope: {},
link: function($scope, element, attrs, ctrl){
ctrl.addToArray();
}
}
}])
.controller('HomeCtrl', ['$scope', function($scope){
this.addToArray = function(){
console.log('method called');
};
}]);
<div ng-app="App">
<div>
<div mult-ecs>multEcs</div>
</div>
</div>