【问题标题】:AngularJS nested directive $pristine and $dirty settingsAngularJS 嵌套指令 $pristine 和 $dirty 设置
【发布时间】:2015-12-21 01:37:12
【问题描述】:

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

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

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

我遇到的问题是 $pristine 和 $dirty 值没有像我预期的那样设置。

我已经修改了下面的小提琴来演示类似的场景.. (代码如下:)

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 - 元素指令本身与外部 div 一样保持 ng-pristine。

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

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

提前谢谢..

【问题讨论】:

    标签: angularjs nested directive


    【解决方案1】:

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

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

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

    【讨论】:

    • 感谢您的建议 - 不幸的是,我无法使用 ngModelController 设置脏状态,因为我需要支持 IE8,因此我受限于旧版本的 AngularJS (1.2.28)。 (编辑过的问题包括这个)。 AngularJS 1.2.28 在 ngModelController 上没有 $setDirty() 方法...
    • 快速和 ugly 修复可能是在 ngModel.$dirty 上的 $scope.$watch 并使用 ng-class 手动设置/删除 ng-dirty 类。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多