Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

angularjs - What is the difference between scope:{} and scope:true inside directive?

I can't find this information about Angular.js and I notice while I was working that those two values work differently. What's the difference?

.directive('foo', function() {

  return {
    scope: true
  };
});

.directive('foo', function() {

  return {
    scope: {}
  };
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Both scope: true and scope:{} will create a child scope for the directive. But,

scope:true will prototypically inherit the properties from the parent(say the controller where the directive comes under) where as scope:{} will not inherit the properties from the parent and hence called isolated

For instance lets say we have a controller c1 and two directives d1 and d2,

app.controller('c1', function($scope){
  $scope.prop = "some value";
});

.directive('d1', function() {
  return {
    scope: true
  };
});

.directive('d2', function() {
  return {
    scope: {}
  };
});

<div ng-controller="c1">
  <d1><d1>
  <d2><d2>
</div>

d1(scope:true) will have access to c1 scope -> prop where as d2 is isolated from the c1 scope.

Note 1: Both d1 and d2 will create a new scope for each directive defined.

Note 2: Apart from the difference between the two, for scope:true - Any changes made to the new child scope will not reflect back to the parent scope. However, since the new scope is inherited from the parent scope, any changes made in the c1 scope(the parent scope) will be reflected in the directive scope.

Tip: Use scope:{} or isolated scope for reusable angular directives. So that you won't end up messing with the parent scope properties


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...