简体   繁体   English

angular 1.2指令范围问题

[英]angular 1.2 directive scope issue

When creating a directive with isolate scope , but no template in the directive, but with some dom inside the directive, the dom inside the directive can not bind to the scope of the directive. 当创建具有isolate scope的指令时,该指令中没有模板 ,但该指令内有一些dom,指令内的dom无法绑定到该指令的范围。

  <div ng-controller="testCtrl">
    {{hehe}}
    <hr/>
    <div test-directive="hello" >
      Directive Data: 
      <div>{{test}}</div>
    </div>
  </div>

angular.module('app',[])
.controller("testCtrl",['$scope', function ($scope) {

  $scope.hehe = "test from controller";

}])
.directive("testDirective",function(){
  return{
    scope: {
      "testDirective": "="
    },
    controller: ['$scope', function ($scope) {

      $scope.test = "test from directive";

    }]
  };
});

Demo 演示

In the demo, there are two angular lib versions, 1.1.5 and 1.2.4, and one of them is commented. 在演示中,有两个有角度的lib版本1.1.5和1.2.4,并注释了其中之一。

The code works with 1.1.5 but not with 1.2.4. 该代码适用于1.1.5,但不适用于1.2.4。

Can someone explain what is happening? 有人可以解释发生了什么吗?

This is a change in 1.2.x. 这是1.2.x中的更改。 The isolate scope is truly isolate and you can only really bind to it from a template inside your directive (defined through template: or templateUrl: ). 隔离范围是真正的隔离范围,您只能从指令内部的模板(通过template:templateUrl:定义)上真正绑定它。

The template in your HTML will never inherit the scope of your directive. HTML中的模板将永远不会继承指令的范围。

The point of isolate scopes is to isolate the internal implementation of your directive from the outer template. 隔离范围的目的是将指令的内部实现与外部模板隔离。 The old behavior dind't fully isolate the directive and made things more coupled. 旧的行为并没有完全隔离指令,并使事情更加紧密。

It is not recommended to use isolate scope unless you are using an internal template in the directive. 除非您在指令中使用内部模板,否则不建议使用隔离作用域。 When not using template: or templateUrl: you should just use scope: true or just no scope at all. 当不使用template:templateUrl:您应该只使用scope: true或根本不使用任何范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM