为什么自定义指令有" ng-dirty"开始上课?

时间:2016-10-13 10:36:39

标签: javascript angularjs angularjs-directive

我希望我的自定义指令(如angular' s指令)支持required选项,因此我在指令中引用了ngModel。但它不喜欢在你输入内容之前没有ng-dirty课程的其他指令。

我该怎么办?

My JSFiddle code

HTML code:

<div ng-app="myDemo" ng-controller="myDemoCtrl">
    <div>{{name}}</div>
    <ul>
        <li ng-repeat="item in items track by $index">{{item}}</li>
    </ul>
    <form>
        <input type="text" required ng-model="name">
        <list ng-model="items" required></list>
    </form>
</div>

CSS代码

form .ng-invalid.ng-dirty {
    border: 1px solid red;
}
form .demo-list.ng-invalid.ng-dirty {
    border: none;
}
form .demo-list.ng-invalid.ng-dirty input {
    border: 1px solid red;
}

JS代码:

angular.module('myDemo', []).controller('myDemoCtrl', function($scope) {
    $scope.name = '';
    $scope.items = undefined;
}).directive('list', function() {
    return {
        restrict: 'E',
        replace: true,
        scope: {},
        require: '?ngModel',
        template: '<div class="demo-list"><input type="text" ng-model="addItems"></div>',
        link: function(scope, element, attrs, ngModelCtrl) {
            if (!ngModelCtrl) {
                return;
            }

            ngModelCtrl.$isEmpty = function(value) {
                return !(angular.isArray(value) && value.length > 0);
            };

            ngModelCtrl.$formatters.push(function(modelValue) {
                return angular.isArray(modelValue) ? modelValue : [];
            });

            ngModelCtrl.$render = function() {
                scope.addItems = ngModelCtrl.$viewValue.join(',');
            };

            scope.$watch('addItems', function() {
                var newList = scope.addItems.length == 0 ? [] : scope.addItems.split(',');
                ngModelCtrl.$setViewValue(newList);
            });
        }
    };
});

更新

it's working, JSFiddle Code

0 个答案:

没有答案