AngularJs指令添加属性,该事件不会被触发
问题描述:
早上好大家好,AngularJs指令添加属性,该事件不会被触发
我有点停留在这个指令,我要的是收到一个JSON字符串从GetProperties中发挥作用,如:
{"class":"someclass","ng-change":"someChange()",ng-click": "someCLick()"}
该指令将创建JSON中的所有属性(它的工作原理),问题是ng- *根本无法工作....任何想法?
HTML:
<div ng-repeat="field in fields">
<input type="text" ng-model="ngModel[field.fieldName]" ng-switch="text" property="{{formParams.getProperties(field.fieldName)}}" update-attr />
</div>
这是指令:
.directive('updateAttr', function() {
return {
restrict: 'A',
replace: true,
scope:{
test:'&'
},
terminate:true,
link: function (scope, elem, attrs) {
if (angular.isDefined(attrs['property']) || attrs['property'].lenght != 0) {
var json = JSON.parse(attrs['property']);
elem.removeAttr('property');
angular.forEach(json, function (value, key) {
elem.attr(key, value);
});
}
},
};
})
这里有一个的jsfiddle:http://jsfiddle.net/nyyfmd0e/16/
答
的问题是,你的link
功能中加入ng-change
属性,后指令已编译,因此Angular不知道它的存在。在添加新属性后,您需要重新编译并替换该指令的元素。
尝试用下面的代码替换您的指令。
.directive('updateAttr', function ($compile) {
return {
restrict: 'A',
replace: true,
terminate: true,
link: function (scope, elem, attrs) {
if (angular.isDefined(attrs['property']) && attrs['property'].lenght != 0) {
var json = JSON.parse(attrs['property']);
angular.forEach(json, function (value, key) {
elem.attr(key, value);
});
elem.removeAttr('property');
var $e = $compile(elem[0].outerHTML)(scope); // <-- recompile
elem.replaceWith($e); // <-- replace with new compiled element
}
},
controller:function($scope){
$scope.test=function(){
console.log('me either');
}
}
};
});
在这种情况下,test()
功能的指令控制器将被调用。如果您删除了指令控制器,则将调用您的应用程序的控制器(在您的小提琴中调用testController
)。
这里有一个工作小提琴供您参考http://jsfiddle.net/JohnnyEstilles/3oaha6z4/。
检查的for-each 'angular.forEach(JSON,函数(值,键){ 的console.log( “ADD” +键); elem.attr(键,值); });' 您将“something1”作为关键字添加了给定值 - 该如何工作? – graphefruit 2014-10-05 09:09:15
我不明白你想要达到什么,你能否详细说明一下?目前你的ngModel引用一个空的对象是可取的吗? – Linial 2014-10-05 10:36:12
@Linial这个脚本是更大的东西的一部分,所以我不得不提取指令并创建一个工作示例^^,如果你看看js小提琴,你可以看到指令正确地创建了新的属性....但在ng-change中,函数test()不会在指令或控制器中调用.... – Aliceiw 2014-10-05 10:59:12