为什么在指令的链接功能中对$ scope进行的更改未在UI上反映出来?

fio*_*say 4 javascript angularjs angularjs-directive

AngularJS指令的link功能更改隔离范围数据未反映在UI中.

这是一个例子:

var myApp = angular.module('myApp', []);

myApp.directive('myDirective', function () {
    return {
        restrict: 'A',
        template: '<span>Title: {{myParams.title}}</span>',
        scope: {
            myParams: '='
        },
        link: function ($scope) {
            // the new value is not reflected in ui
            $scope.myParams.title = 'this is myDirective';
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

HTML:

 <div my-directive my-params="{title: 'this is title'}"></div>
Run Code Online (Sandbox Code Playgroud)

我想要显示HTML页面,this is myDirective但实际上它是this is title.

另外,你能解释为什么它会这样显示.谢谢

Nik*_*los 5

原因是它my-params="{title: 'this is title'}"是一个常量表达式而不是可赋值的.因此,即使您尝试覆盖该'title'属性,它也会从常量中被覆盖.检查这个小提琴.它包含您的代码,并设置为与Angular 1.4一起使用.区别在于指令如上所述使用一次,而一次使用来自控制器的可变的非常量值:

<div ng-app="app" ng-controller="Ctrl as ctrl">
  <div my-directive my-params="{title: 'this is title'}"></div>
  <div my-directive my-params="data"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

第二个实例(非常量表达式)有效.

现在尝试将Angular版本更改为1.2.请注意,现在Angular会抛出无限的摘要错误:

VM1033 angular.js:9101 Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: [["fn: parentValueWatch; newVal: {\"title\":\"this is title\"}; oldVal: {\"title\":\"this is title\"}"],["fn: parentValueWatch; newVal: {\"title\":\"this is title\"}; oldVal: {\"title\":\"this is title\"}"],["fn: parentValueWatch; newVal: {\"title\":\"this is title\"}; oldVal: {\"title\":\"this is title\"}"],["fn: parentValueWatch; newVal: {\"title\":\"this is title\"}; oldVal: {\"title\":\"this is title\"}"],["fn: parentValueWatch; newVal: {\"title\":\"this is title\"}; oldVal: {\"title\":\"this is title\"}"]]
Run Code Online (Sandbox Code Playgroud)

指令(即my-params="{title: 'this is title'}")中给出的表达式试图覆盖指令范围属性(总是在1.2中创建一个新对象,因此无限摘要).