我正在尝试基于模型动态生成表单输入和关联的操作菜单。我能够传递要使用的字段和菜单,但我不知道如何配置 ng-click 以调用模型中定义的相应函数。见小提琴:http: //jsfiddle.net/ahonaker/nkuDW/
HTML:
var myApp = angular.module('myApp',[]);
myApp.directive('myDirective', function($compile) {
return {
restrict: "E",
replace: true,
scope : {
field: '=',
label: '=',
menu: '='
},
link: function (scope, element, attrs) {
element.html('{{label}}: <input ng-model="field"> <ul ng-repeat="item in menu"<li><a ng-click="item.func">{{item.title}}</a></li></ul>');
$compile(element.contents())(scope);
}
}
});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.status = 'You have not picked yet';
$scope.menu = [
{ "title" : "Action 1", "func" : "ActionOne()"},
{ "title" : "Action 2", "func" : "ActionTwo()"},
]
$scope.fieldOne = "I am field 1";
$scope.fieldTwo = "I am field 2";
$scope.ActionOne = function() {
$sopce.status = "You picked Action 1";
}
$scope.ActionOne = function() {
$sopce.status = "You picked Action 2";
}
}
JS:
<div ng-app = "myApp">
<div ng-controller="MyCtrl">
<ul>
<p><my-directive field="fieldOne" label="'Field 1'" menu="menu"></my-directive></p>
<p><my-directive field="fieldTwo" label="'Field 2'" menu="menu"></my-directive></p>
</ul>
Hello, {{status}}!
</div>
</div>
任何帮助,将不胜感激。我在指令中尝试了以下 ng-click 方法
ng-click={{item.func}}
ng-click="item.func"
ng-click="{{item.func}}"
我究竟做错了什么?或者有没有更好的方法来做到这一点(包括要调用的功能的菜单结构必须来自模型,以便我构建通用表单生成能力)。