0

This is from angular doc about ng-init.

The ngInit directive allows you to evaluate an expression in the current scope.

But if I use ng-init along with custom directive, and the directive use different scope difinition, the variable by ng-init will have different scope.

demo

<body ng-app="transcludeScope" ng-init="test='test'">
    <div truescope ng-init="test2='test2'">Transcluded:<p>test: {{test}}</p><p>test2: {{test2}}</p><p>test3: {{test3}}</p></div>
    <hr>
    <div isolatescope ng-init="test3='test3'">Transcluded:<p>test: {{test}}</p><p>test2: {{test2}}</p><p>test3: {{test3}}</p></div>
    </div>
</body>



angular.module('transcludeScope', [])
.directive('truescope', function() {
  return {
    transclude: true,
    scope: true,
    template: "<p>test: {{test}}</p><p>test2: {{test2}}</p><div ng-transclude></div>"
  }
})
.directive('isolatescope', function() {
  return {
    transclude: true,
    scope: {},
    template: "<p>test: {{test}}</p><p>test3: {{test3}}</p><div ng-transclude></div>"
  }
});

From the result, test2 is only available inside directive while test3 is available whole app.

can anyone explain their behavior? Thanks :-)

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
tjfdfs
  • 729
  • 10
  • 26
  • You completely ignored the gigantic red warning message on that documentation page that you copied your description from. `ngInit` is a directive, priority 450, which means that it may have undesired side effects when interacting with other directives, especially ones which have a lower priority, or create a child scope themselves. – Claies Dec 09 '15 at 03:26
  • @Claies I follow the warning suggest in ng doc in real project code, this problem is happen when I create a demo code to explain directive's scope, which I don't use any controller because the demo is very simple to use controller. – tjfdfs Dec 09 '15 at 03:34
  • @Claies maybe it is a side effect... – tjfdfs Dec 09 '15 at 03:35
  • I actually don't think this is related to `ngInit`, but related to how `transclude` interacts with `scope : { }`. This may give you more insight: http://stackoverflow.com/questions/16653004/confused-about-angularjs-transcluded-and-isolate-scopes-bindings – Claies Dec 09 '15 at 03:38
  • @tjfdfs This may also help you. http://stackoverflow.com/questions/34038699/why-directive-has-scope – Bhojendra Rauniyar Dec 09 '15 at 03:44
  • @BhojendraNepal thanks – tjfdfs Dec 09 '15 at 04:02

0 Answers0