AngularJS-将函数传递给指令 [英] AngularJS - pass function to directive
本文介绍了AngularJS-将函数传递给指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个angularJS示例
I have a example angularJS
<div ng-controller="testCtrl">
<test color1="color1" updateFn="updateFn()"></test>
</div>
<script>
angular.module('dr', [])
.controller("testCtrl", function($scope) {
$scope.color1 = "color";
$scope.updateFn = function() {
alert('123');
}
})
.directive('test', function() {
return {
restrict: 'E',
scope: {color1: '=',
updateFn: '&'},
template: "<button ng-click='updateFn()'>Click</button>",
replace: true,
link: function(scope, elm, attrs) {
}
}
});
</script>
</body>
</html>
我想要当我单击按钮时,将出现警报框,但什么也没显示.
I want when I click button, the alert box will appear, but nothing show.
有人可以帮助我吗?
推荐答案
要从隔离作用域指令内部在父作用域中调用控制器函数,请像OP所说的那样在HTML中使用dash-separated
属性名.
To call a controller function in parent scope from inside an isolate scope directive, use dash-separated
attribute names in the HTML like the OP said.
如果要向函数发送参数,请通过传递对象来调用函数:
Also if you want to send a parameter to your function, call the function by passing an object:
<test color1="color1" update-fn="updateFn(msg)"></test>
JS
var app = angular.module('dr', []);
app.controller("testCtrl", function($scope) {
$scope.color1 = "color";
$scope.updateFn = function(msg) {
alert(msg);
}
});
app.directive('test', function() {
return {
restrict: 'E',
scope: {
color1: '=',
updateFn: '&'
},
// object is passed while making the call
template: "<button ng-click='updateFn({msg : \"Hello World!\"})'>
Click</button>",
replace: true,
link: function(scope, elm, attrs) {
}
}
});
这篇关于AngularJS-将函数传递给指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文