gpt4 book ai didi

javascript - AngularJS:如何将参数/函数传递给指令?

转载 作者:IT王子 更新时间:2023-10-29 03:03:41 24 4
gpt4 key购买 nike

this Fiddle ,我必须更改什么,使用我在 HTML 中定义的参数评估模板中的表达式?保存按钮应该调用 Controller 的 blabla() 函数,因为我传递了它?

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();
};
}
}
});

我真的看不透。感谢您的帮助!

最佳答案

您可以按照 Roy 的建议使用 property: '=' 设置两种方式的数据绑定(bind)。因此,如果您希望将 keyvalue 都绑定(bind)到本地范围,您可以这样做

scope: {
key: '=',
value: '='
},

由于您正在传递这些值,因此您可以在指令的 Controller 中访问它们。但是如果你想在父范​​围的上下文中运行一个函数,这似乎是你想用 accept 属性做的,那么你需要像这样告诉 angular

scope: {
accept: "&"
}

现在,您可以从您的save 方法调用通过accept

传递的函数
controller: function($scope, $element, $attrs, $location) {
$scope.save= function() {
$scope.accept()
};
}

这是一个 jsfiddle

关于javascript - AngularJS:如何将参数/函数传递给指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13725938/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com