如何使用模型属性为变量NG-点击 [英] how to use a model property as variable ng-click
问题描述
我想有NG-点击存储在我的模型字符串函数调用。
我不能使用NG点击=m.func,如果我使用NG点击={{m.func}}IST也不能正常工作。
它也像角1.2.0抛出一个错误的情况下,NG-点击={{m.func}}。
我如何才能把它的工作?
< DIV NG-应用=对myAppNG控制器=myCtrl>
< DIV NG重复=M模型>< A HREF =#NG点击={{m.func}}> {{m.caption}}< / A>&LT ; / DIV>
< / DIV>VAR应用= angular.module('对myApp',[]);app.controller('myCtrl',函数($范围){
$ scope.model = [
{
标题:呼我一个'
FUNC:callme_a()
},
{
标题:呼我B',
FUNC:callme_b()
}
] $ scope.callme_a =功能(){
警报(称为);
} $ scope.callme_b =功能(){
警报(称为B);
}
});
这可能是之前的评估为一个字符串,NG-点击被附加一个事件侦听器与NG-点击属性DOM。
所以,我重写了超时ngclick让你想要什么工作:)
VAR应用= angular.module('对myApp',[]);
app.directive('ngClick',['$超时','$解析',函数($超时,$解析){
返回{
编译:函数($元素,属性){
返回功能(范围,元素,属性){
//我裹在$超时此链接功能code
$超时(函数(){
变种FN = $解析(ATTR [ngClick]);
$(元素[0])。在(点击,函数(事件){
范围。$应用(函数(){
FN(范围,{$事件:事件});
});
});
})
};
}
};
}]);
(这里是源$ C $ C为ngClick - 的https://github.com/angular/angular.js/blob/master/src/ng/directive/ngEventDirs.js)
在这里检查拨弄演示 - http://jsfiddle.net/R2Cc9/5/
I'd like to have function calls for ng-click stored as strings in my model. I can't use ng-click="m.func", and if i'm using ng-click="{{m.func}}" ist also not working.
It also looks like angular 1.2.0 throws an error in case of ng-click="{{m.func}}".
How can I bring it to work?
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="m in model"><a href="#" ng-click="{{m.func}}">{{m.caption}}</a></div>
</div>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.model = [
{
caption: 'callme a',
func : 'callme_a()'
},
{
caption: 'callme b',
func : 'callme_b()'
}
]
$scope.callme_a = function() {
alert("called a");
}
$scope.callme_b = function() {
alert("called b");
}
});
It could be that ng-click is attaching an event listener to the dom with the ng-click attribute before it's evaluated to a string.
So, I've overridden the ngclick with a timeout to make what you want work :)
var app = angular.module('myApp', []);
app.directive('ngClick', ['$timeout','$parse', function($timeout, $parse) {
return {
compile: function($element, attr) {
return function(scope, element, attr) {
//I've wrapped this link function code in a $timeout
$timeout(function() {
var fn = $parse(attr["ngClick"]);
$(element[0]).on("click", function(event) {
scope.$apply(function() {
fn(scope, {$event:event});
});
});
})
};
}
};
}]);
(Here is the source code for ngClick - https://github.com/angular/angular.js/blob/master/src/ng/directive/ngEventDirs.js)
Check the fiddle here with the demo - http://jsfiddle.net/R2Cc9/5/
这篇关于如何使用模型属性为变量NG-点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!