动态向元素添加属性不起作用

时间:2017-07-04 08:00:21

标签: javascript html angularjs angularjs-directive

我写了一个指令来获取带有ng-model指令的所有元素,并向它们添加ng-change属于某个值。添加到DOM的属性。但是它们中的值(函数)不会调用。

我的指示

angular
    .module('myApp')
    .directive('updateFields', updateFields);
updateFields.$inject = ['$timeout', '$compile'];
function updateFields($timeout, $compile) {
    return {
        restrict: 'E',
        link: function (scope, element, arrt) {
            $timeout(() => {
                var elements = angular.element("[ng-model]");
                console.log(elements);
                for (var i = 0; i < elements.length; i++) {
                    var el = elements[i];
                    var fullProperty = elements[i].getAttribute("ng-model");
                    var property = fullProperty.replace("vm.Account.", '');
                    var ngChangeAttr = elements[i].attributes["ng-change"];

                    if (ngChangeAttr) {
                        el.setAttribute('ng-change', ngChangeAttr.value + ";" + "vm.actions.updateField( " + "'" + property + "'," + fullProperty + ")");
                    } else {
                        el.setAttribute('ng-change', "vm.actions.updateField( " + "'" + property + "'," + fullProperty + ")");
                    }
                   $compile(el)(scope);
                }
            });
        }
    }
}

0 个答案:

没有答案