0

I got confused a bit about whether can we create multiple instance of controller and that to in nested form for eg -

<div ng-controller="abc"> 
   <form ng-submit="call()">
       <input type=text ng-model="content"/>
   </form>
   <div ng-controller = "abc">
       <form ng-submit="call()">
            <input type=text ng-model="content"/>
       </form>
   </div>
</div>

i just want to know that if i use the same model with other instance of controller, so model value would be same or different. Similar to static variable ?

1 Answer 1

5

i just want to know that if i use the same model with other instance of controller, so model value would be same or different. Similar to static variable ?

All declarations of ng-controller create a new instance of the controller. So, if you had two instances side by side, like this:

<div ng-controller="abc">
    <input type=text ng-model="content"/>
</div>
<div ng-controller="abc">
    <input type=text ng-model="content"/>
</div>

plunker

then, all of the $scope properties of each would be completely independent.

When a ng-controller is nested, then its scope inherits the parent controller's scope. So for this you'd expect that content refers to the same scope property:

<div ng-controller="abc">
    <input type=text ng-model="content"/>
    <div ng-controller="abc">
       <input type=text ng-model="content"/>
    </div>
</div>

plunker

However, since content is not defined directly in the controller something strange happens. If you fill in the parent input first. Both, inputs become bound to the same scope property. However, if you fill in the child input first, they are independent!

This can be confusing until you understand that Angular is being lazy when it creates the property on the scope. content is null at first on both scopes. It is only when it has a value that it will inherit.

So, what do you do if you want to keep things separate? Add an initial value to a $scope property inside the controller:

app.controller('abc', function($scope) {

     $scope.content = '';
});

plunker

This way, each separate controller instance is initialized with its own content property.

Hope this helps.

Sign up to request clarification or add additional context in comments.

1 Comment

And how are the scope properties passed from the directive into a nested controller?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.