AngularJs Directive to add Attributes, the events are not triggered

前端 未结 1 897
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-23 02:30

Good morning everybody,

I\'m a bit stuck on this directive, what I want is to receive a JSON string from the getProperties function like:

{\"class\":\"s         


        
1条回答
  •  太阳男子
    2021-01-23 03:01

    The problem is that your adding the ng-change attribute during the link function, after the directive has been compiled, therefore Angular is not aware if its existence. You need to recompile and replace the element of the directive after you add the new attributes.

    Try replacing your directive with the code below.

    .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');
                }                
            }
        };
    });
    

    In this case the test() function in the directive controller will be called. If you remove the directive controller, then one your application's controller (called testController in your Fiddle) will be invoked.

    Here a working Fiddle for your reference http://jsfiddle.net/JohnnyEstilles/3oaha6z4/.

    0 讨论(0)
提交回复
热议问题