AngularJS:如何将参数/函数传递给指令? [英] AngularJS: How to pass arguments/functions to a directive?
问题描述
看看 this Fiddle,我需要改变什么,模板中的表达式使用我在 HTML 中定义的参数?保存按钮应该调用控制器的 blabla()
函数,因为我传递了它?
Look at this Fiddle, what do I have to change, that the expressions in the template get evaluated using the arguments I defined in the HTML? The SAVE-button should call the blabla()
-function of the controller, since I pass it?
var myApp = angular.module('MyApp',[])
myApp.directive('editkeyvalue', function() {
return {
restrict: 'E',
replace: true,
scope: {
accept: "expression"
},
template : '<div><label class="control-label">{{key}}</label>' +
'<label class="control-label">{{key}}</label>' +
'<input type="text" ng-model="value" />'+
'<button type="button" x-ng-click="cancel()">CANCEL</button>' +
'<button type="submit" x-ng-click="save()">SAVE</button></div>',
controller: function($scope, $element, $attrs, $location) {
$scope.save= function() {
$scope.accept();
};
}
}
});
我真的看不透.感谢帮助!
I do not really see through that. Thanks for help!
推荐答案
您可以使用 property: '='
设置两种方式的数据绑定,正如 Roy 建议的那样.因此,如果您希望 key
和 value
都绑定到本地范围,您会这样做
You can set two way data binding with property: '='
as Roy suggests. So if you want both key
and value
bound to the local scope you would do
scope: {
key: '=',
value: '='
},
由于您正在传递这些值,因此您可以在指令的控制器中访问它们.但是如果你想在父作用域的上下文中运行一个函数,这似乎是你想要用 accept
属性做的,那么你需要像这样告诉 angular
Since you are passing these values, you have access to them in your directive's controller. But in case you want to run a function in the context of the parent scope, which seems to be what you want to do with the accept
attribute, then you would need to tell angular like this
scope: {
accept: "&"
}
现在,从您的 save
方法中,您可以调用通过 accept
Now, from your save
method you could call the function passed via accept
controller: function($scope, $element, $attrs, $location) {
$scope.save= function() {
$scope.accept()
};
}
这是一个 jsfiddle
这篇关于AngularJS:如何将参数/函数传递给指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!