1

I was really confused with this example from angular documentation plunker and angular docs

here I have removed $parent inside a ng-repeat but it is still working fine..?

why do we need to add that in ng-repeat because each iteration will have its own $scope and this will evaluate. why do we required previous or $parent scope.

santhosh
  • 1,919
  • 3
  • 21
  • 33

2 Answers2

1

It depends upon what you are trying to achieve, if you are not using controller As syntax, you would need $parent to access the parent controllers scope in a nested structure.

<div ng-controller="ParentController">
    <div ng-controller="ChildController">
    </div>
</div>

Then you can access the parent scope as follows

function ParentController($scope) {
    $scope.states= ["Chennai", "Kerala", "Spain"];
}

function ChildController($scope) {    
}

Now you could do something from your view...

<div ng-app ng-controller="ParentController">
    <div ng-controller="ChildController">
       {{$parent.states}}
    </div>
</div>

Now coming to case of your comment on a isolated scope, we could use $parent to access the property in parent scope but you could use the scope property (@ , = , &) where you can specify which scope properties you need to work with.

Thalaivar
  • 23,282
  • 5
  • 60
  • 71
0

$parent is often use when people don't really know what they're doing of with some kind of tricky directives.

Usually if you don't want to have to use $parent. Use dot notation :

$scope.toto = "titi";//not a dot notation
$scope.fields = {toto:"titi"};// dot notation

Having an intermediary object will make sure that you won't have any problems between scope that inherits from each others. This is a du to a limit of javascript.

Walfrat
  • 5,363
  • 1
  • 16
  • 35
  • can you give me an example for the tricky directive as you have mentioned – santhosh Apr 11 '16 at 11:30
  • @santhosh: you would use the scope property of the directive to access the properties from the parent scope via (@, = and &) much preferred way. – Thalaivar Apr 11 '16 at 11:35
  • @santhosh i just saw some people doing that on the net but in the end i never had to use $parent myself as long as i respected the dot notation. I can just say that it may happens with directives that inherits their scope from parent's scope ( **scope:true** in the definition of the directive). – Walfrat Apr 11 '16 at 11:47