0

我有点卡在添加属性并重新编译元素的指令上。

如果我对指令 ng-change 有一个范围,则不再触发(没有它它可以工作)。我的测试基于这个答案

的HTML

<div ng-app="myApp">
    <div ng-controller='testController'>
        <div ng-repeat="field in fields">
            <input type="text" ng-model="ngModel[field.fieldName]" property="{{formParams.getProperties(field.fieldName)}}" update-attr ng-change="test()" />
        </div>
    </div>
</div>

指令:

angular.module('myApp', [])
    .controller('testController', function ($scope) {
        $scope.properties = {
            "something": {
                "style": "float:left;"
            },
                "something2": {
                "style": "float:right;"
            }
        };

        $scope.ngModel = {};
        $scope.fields = [{
            fieldName: 'something'
        }, {
            fieldName: 'something2'
        }];
        $scope.test = function () {
            alert('i dont get triggered');
        };
        $scope.formParams = {
            getProperties: function (fieldName) {
                return $scope.properties[fieldName];
            }
        };
    })
    .directive('updateAttr', function ($compile) {
        return {
            restrict: 'A',
            replace: true,
            terminate: true,
            scope: {
                ngModel : '='
            },
            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);
                    elem.replaceWith($e);
                }
            }
        };
    });

这里是小提琴的一个分支,用于测试指令的范围:fiddle

你有什么建议吗?

4

1 回答 1

0

我发现为什么 ng-change 没有被触发,所以我分享了答案:

当我们在指令上添加范围属性时,会创建一个新范围。所以我们必须使用 $scope.$parent 进行编译。我已经用更正更新了小提琴。

于 2015-05-18T17:57:17.623 回答