AngularJs指令添加属性,事件不被触发

2023-12-15

大家早上好,

我对这个指令有点困惑,我想要的是从 getProperties 函数接收一个 JSON 字符串,例如:

{"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/


问题是你添加了ng-change期间的属性link函数,在指令编译后,因此 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/.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

AngularJs指令添加属性,事件不被触发 的相关文章

随机推荐