Why are my AngularJS directives sharing scope?

后端 未结 4 458
不知归路
不知归路 2020-12-15 21:29

I\'ve tried to make a simple directive which displays a name and allows it to be change. When I put multiple directive on the name page they all seem to share the name attri

4条回答
  •  渐次进展
    2020-12-15 21:53

    As mentioned in previous answers, the default behavior of AngularJS directives is to share the scope that they are included in. This behavior is changed via the scope parameter in the directive definition object.

    You can view the documentation for the scope argument in this section of the AngularJS documents: http://docs.angularjs.org/api/ng.$compile#description_comprehensive-directive-api_directive-definition-object

    This argument has three options:

    1. scope: false - the default behavior of sharing the scope the directive is included in

    2. scope: true - create a new scope for the directive that acts like other child scopes and prototypically inherits from its parent scope

      • See Example 1
    3. scope: {} - create an isolated scope that does not prototypically inherit from its parent scope

      • See Example 2

    As you can see with the JSBin examples, both options 2 and 3 will work for your example. The difference is whether you want your new scopes isolated or not.

    The directives section of the AngularJS guide has a good section on why isolated scope can help create better reusable modules with directives: AngularJS Guide: Isolating the Scope of a Directive

提交回复
热议问题