为什么在这种情况下,setViewValue() 不会更新所有位置的值

Why setViewValue() is not updating values on all places in this case?

本文关键字:更新 位置 这种情况下 setViewValue 为什么      更新时间:2023-09-26

index.html是:

<!DOCTYPE html>
<html ng-app="myApp">
    <head>
        <script src="js/angular.js" type="text/javascript"></script>
        <script src="js/app.js" type="text/javascript"></script>
    </head>
    <body>
        <div>TODO write content </div>
        <input test type="text" ng-model="name" >
        <h1>name: {{name}}</h1>
    </body>
</html>

app.js是:

var app = angular.module('myApp', []);
app.directive('test', function () {
    return {
        require: '?ngModel',
        link: function ($scope, $element, $attr, controller) {
            if (!controller) {
                console.log("controller of ngModel not found");
                return;
            } else {
                console.log("controller of ngModel found");
                controller.$setViewValue('qwerty');
            }
        }
    };
});

在上面的 link 函数示例中,我正在使用 DDO 中指定的选项访问ngModel指令controller require。然后使用该对象,我正在更新 name 的值,这在index.html内部<h1>name: {{name}}</h1>更新,但在<input test type="text" ng-model="name">内部index.html内更新。为什么它在一个地方更新而不在另一个地方更新?

代码 @ plnkr.co

来自角度源:

同样重要的是要注意,$setViewValue不会调用 以任何方式$render或更改控件的 DOM 值。如果我们愿意 以编程方式更改控件的 DOM 值,我们应该更新 ngModel范围表达式。

在此示例中,您可以: $parse($attr.ngModel).assign($scope, 'qwerty')

$setViewValue不会直接更新$modelValue,您需要在控制器上触发$render()函数ngModel该函数,该函数会将该$viewValue传递给$modelValue,因此您将在页面上获得绑定。

命令

app.directive('test', function () {
    return {
        require: '?ngModel',
        link: function ($scope, $element, $attr, controller) {
            if (!controller) {
                console.log("controller of ngModel not found");
                return;
            } else {
                console.log("controller of ngModel found");
                controller.$setViewValue('qwerty');
                controller.$render(); //to update $modelValue
            }
        }
    };
});

分叉的普伦克