我们执行了下一个指令:



angular.module('app', [])
  .directive('dIsolatedWorks', function() {
    return {
      scope: {
        prop: '='
      },
      template: '<span>{{name}}: {{prop}}</span>',
      link: function(scope) {
        scope.name = 'isolated';
        scope.prop = 'link';
      }
    };
  })
  .directive('dIsolated', function() {
    return {
      scope: {
        prop: '@'
      },
      template: '<span>{{name}}: {{prop}}</span>',
      controller: function($scope) {
        $scope.prop = 'controller';
      },
      link: function(scope) {
        scope.name = 'isolated';
        scope.prop = 'link';
      }
    };
  });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div d-isolated-works prop="attribute"></div>
  <div d-isolated prop="attribute"></div>
</div>





实际上,在执行过程中,我确定对scope.prop字段的分配将更改该变量,并且该变量将显示为'link',而不是'attribute'
但是目前,我们看到的是实际值是isolated: attribute
但是,可以通过将字符串分配更改为对象分配来简单地解决。

你能解释这种行为吗?

最佳答案

较小的更改会产生相同的结果,两个前缀=和@



angular.module('app', [])
.directive('dIsolatedWorks', function () {
return {
    scope: {
        prop: '='
    },
    template: '<span>{{name}}: {{prop}}</span>',
    link: function (scope) {
        scope.name = 'isolated';
        scope.prop = 'link';
    }
};
})
.directive('dIsolated', function ($timeout) {
return {
    scope: {
        prop: '@'
    },
    template: '<span>{{name}}: {{prop}}</span>',
    controller: function ($scope) {
        $scope.prop = 'controller';
    },
    link: function (scope, element, attr) {
        scope.name = 'isolated';
        $timeout(function(){  });
        $timeout(function(){
            console.log('Still I found attrib value: ',scope.prop);

          scope.prop = 'link'; // this will change it
            });
        //scope.prop = 'link';

    }
};
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
    <div d-isolated-works prop="attribute"></div>
    <div d-isolated prop="attribute"></div>
</div>





但是从概念上讲


  @绑定用于传递字符串。这些字符串支持{{}}
  内插值的表达式。例如: 。插值
  表达式是根据指令的父范围求值的。
  
  =绑定用于双向模型绑定。父范围中的模型链接到指令隔离范围中的模型。更改为一个
  模型会影响另一个,反之亦然。


通过牢记上述概念,分析:

1-当我们使用前缀'@'模板定义范围时,总是从attrib获取值(因此link scope.prop不起作用)

2-然后创建scope并为其分配attrib字符串值



3-第二个摘要循环将运行时(在ng-clickng-model$timeout上),它将更改值

4-请参阅上述代码中的$timeout以了解(运行!)

快乐的帮助!

关于javascript - AngularJS属性绑定(bind)优先级,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33187436/

10-09 17:39
查看更多