为什么数据在指令外更改?

时间:2016-04-04 07:11:24

标签: javascript angularjs

我无法弄清楚为什么数据在external div中的指令之外发生变化,我认为它应该与控制器行为相同,因为external Div没有包裹在directive和{ {1}},所以仍然应该没有评价,请帮助弄清楚原因,谢谢。

Plunker



controller

(function(angular) {
  angular.module('myApp', [])
    .directive('myDirective', function() {
      return {
        link: function(scope) {
          scope.dataFormDirective = "directiveData";
        }
      }
    })
    .controller('myCtrl', function($scope) {
      $scope.data = "controllerData";
    })
})(window.angular);




1 个答案:

答案 0 :(得分:1)

通过@SmokeyPHP评论,添加scope:true将解决此问题。

这是因为该指令将共享父作用域但控制器,在我的示例中,指令作用域将是$ rootscope,因为没有控制器包装

(function(angular) {
  angular.module('myApp', [])
    .directive('myDirective',function() {
      return {
        scope:true,
        link: function(scope) {
              scope.dataFormDirective = "directiveData";
        }
      }
    })
    .controller('myCtrl', function($scope) {
        $scope.data = "controllerData";
    })
})(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<body ng-app="myApp">

  <div>external div</div>
  <div>data: {{data}}</div>
  <div>dataFormDirective: {{dataFormDirective}}</div>
  </br>

  <div ng-controller="myCtrl">
    myCtrl
    <div>data : {{data}}</div>
    <div>dataFormDirective:{{dataFormDirective}}</div>
  </div>
  </br>

  <div my-directive>myDirective {{dataFormDirective}}</div>

</body>