0

I have got two separate divs as shown in the code below. What I am trying to do is update the Controller from first div and then detect the changes in the second div using the same controller. When I press the button, 'i am here' gets printed on the console but the data in 2nd div won't update. It should change to "clicked".

<html ng-app="app">
<head>
    <title></title>
</head>
<body>

    <h1>Divs below should not be nested</h1>

    <div id="notNested1" ng-controller="Controller1">
        <button ng-click="buttonClick()">Click me</button>
    </div>
    <div id="notNested2" ng-controller="Controller1">
        <p>{{paragraph}}</p>
    </div>

    <script type="text/javascript" src="libs/angular/angular.js"></script>

    <script>
        var app = angular.module('app', []);

        function Controller1($scope) {

            $scope.paragraph = 'initial';

            $scope.buttonClick = function () {
                console.log('i am here');
                $scope.paragraph = "clicked";
            };
        }
    </script>
</body>
</html>

How can I fix this problem? Also what is the problem here? Is it because the $scope is different for both divs?

Thanks

1
  • 2
    common misconception when learning to use angular is that instances of controller will be the same, they aren't. Each element will have it's own instance Commented Jun 13, 2014 at 0:46

1 Answer 1

1

You should probably share the data using a service/factory.

You could also create a parent controller with the data there, and reference it from the child controllers, but a shared service seems better.

Yes you have 2 separate scopes, so they do not interact with each other.

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

2 Comments

That means I should have two separate controllers. First controller broadcasts the event and second controller catches the event and then update the scope? My other question is, is there a way to do it with single controller?
I have done it using two separate controllers, and by firing broadcast event. I am also maintaining a separate shared factory, because at times I need to check if the data is selected in first 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.