Angularjs将ng-model链接到指令中的隔离范围

时间:2014-08-22 14:58:12

标签: angularjs angularjs-directive angularjs-scope

我想要一个小的属性指令,它允许我动态更改它所附加的输入元素的约束。用法如下:

<input type="text" ui-constraints-field data-ng-model="mydata" data-constraints="myconstraints" />

在控制器中:

$scope.mydata = "test string";
$scope.myconstraints = [{key: "required", value: "true"}];

请注意,数据或约束可能随时发生变化。所以我写了这个:

myApp.directive('uiConstraintsField', [function(){

    function applyConstraints(scope, element){
        //remove old constraints
        if(scope.old !== undefined && scope.old !== null){
            for (var i = 0; i < scope.old.length; i++) {
                element.removeAttr(scope.old[i].key);
            }
        }

        //apply new constraints
        if(scope.constraints !== undefined && scope.constraints !== null){
            for (var i = 0; i < scope.constraints.length; i++) {
                var constraint = scope.constraints[i];
                element.attr(constraint.key, constraint.value);
            }
        }

        //newly passed constraints now will be old constraints
        scope.old = scope.constraints;
    }

    return {
        restrict : 'A',
        require: 'ngModel',
        scope : {
            constraints : '=constraints'
        },
        link : function(scope, element, attrs){
            scope.old = scope.constraints;
            scope.$watch("constraints", function(){
                applyConstraints(scope, element);
            });
        }
    };

}]);

正在正确更新约束,但模型未链接。如何链接模型以便在文本框中显示和更新mydata?谢谢:)

- EDIT--
我正在使用angular v 1.0.3,我无法将其更改为更新版本。这似乎导致了这个问题 plnkr

1 个答案:

答案 0 :(得分:0)

好的,我在我的帖子中发布了一个更好的解决方案,而且这个解决方案适用于旧版本的Angular(在我的情况下为1.0.3)以及最新版本。这是:

myApp.directive('uiConstraints', [function(){

    function applyConstraints(element, newVal, oldVal){
        //remove old constraints
        if(oldVal !== undefined && oldVal !== null){
            for (var i = 0; i < oldVal.length; i++) {
                element.removeAttr(oldVal[i].key);
            }
        }

        //apply new constraints
        if(newVal !== undefined && newVal !== null){
            for (var i = 0; i < newVal.length; i++) {
                var constraint = newVal[i];
                element.attr(constraint.key, constraint.value);
            }
        }
    }

    function link(scope, element, attrs){
        scope.$watch(attrs.uiConstraints, function(newVal, oldVal){
            applyConstraints(element, newVal, oldVal);
        });
    }

    return {
        restrict : 'A',
        link : link
    };

}]);

这种指令的用法如下:

<textarea ui-constraints="myConstraints" ng-model="myData" />

在控制器中声明适当的值(myConstraints和myData) 感谢大家尝试提供帮助:)