AngularJS 嵌套指令 $pristine 和 $dirty 设置

AngularJS nested directive $pristine and $dirty settings

我正在编写的指令有问题。

在指令的模板中还有另一个元素指令。

本质上,外部指令是内部指令的装饰器,增加了更多功能..

我遇到的问题是 $pristine 和 $dirty 值没有按照我的预期进行设置。

我修改了下面的 fiddle 来演示类似的场景。 (代码如下:)

HTML

<body ng-app="demo" ng-controller="DemoController">
<h3>rn-stepper demo (3/5)</h3>
Model value : {{ rating }}<br>
<hr>
<div ng-model="rating" rn-stepper></div>
</body>

JS

angular.module('demo', [])

.controller('DemoController', function($scope) {
    $scope.rating = 42;      
})

.directive('test', function() {
    return {
        restrict: 'E',
        scope: {
            ngModel: '=ngModel'
        },
        template: '<input type="text" ng-model="ngModel"></input>'
    };
})

.directive('rnStepper', function() {
    return {
        restrict: 'AE',
        scope: {
            value: '=ngModel'
        },
        template: '<button ng-click="decrement()">-</button>' +
                  '<div>{{ value }}</div>' +
                  '<button ng-click="increment()">+</button>' +
                  '<test ng-model="value"></test>',
        link: function(scope, iElement, iAttrs) {
            scope.increment = function() {
                scope.value++;
            }
            scope.decrement = function() {
                scope.value--;
            }
        }
    };
    });

http://jsfiddle.net/qqqspj7o/

模型按预期共享,当我更改文本输入中的值或使用滑块时,绑定有效 - 但是如果我更新文本输入中的值,只有文本输入被标记为 ng -dirty - element 指令本身与外部 div 一样保持 ng-pristine。

我不明白这是为什么,值没有传播到元素?这是预期的行为 - 如果是这样,我如何将 ng-dirty 等值传播到元素指令和外部 div..

注意:我只能使用Angular v 1.2.x 因为代码需要兼容IE8.

提前致谢..

通常在指令中您应该避免 =value 绑定,并直接使用 ngModelController.

这个话题在这里讨论有点复杂,但是网上有很多很棒的教程我给你推荐这个: using ngModelController 它解释了使用 ngModel 的基础知识,还介绍了装饰器。

当您直接使用 ngModel 时,您可以直接在代码中设置有效性和状态 (dirty/touched/pristine),您还可以通过 $setViewValue().[=15= 设置模型值]