Can I use one controller updating two views in AngularJS?

All we need is an easy explanation of the problem, so here it is.

Is it possible, to have two views bound to one controller, so that both views get updated no matter where the data was changed (view1, view2 or in the model)? It should work like this example (removed clutter).

<script>
    angular.module('foobar', []).controller('ContentCtrl', ['$scope', function($scope) {
        $scope.content = {'title': 'Foo', 'subtitle': 'Bar', 'text': 'desc'};
    }]);
</script>

<form action="#" ng-controller="ContentCtrl">
    <input type="text" ng-model="content.title">
    <input type="text" ng-model="content.subtitle">
    <textarea ng-model="content.text"></textarea>
</form>

<div ng-controller="ContentCtrl">
    <input type="text" ng-model="content.title">
    <input type="text" ng-model="content.subtitle">
    <textarea ng-model="content.text"></textarea>
</div>

Here is a Plunker: http://plnkr.co/edit/UDs10RhG7mJR8813epwO?p=preview

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

There’s no reason you can’t do this, but the same object has to be in the scope of both controllers. See http://plnkr.co/edit/ILzGCs9AYiPTETE92KTm?p=preview

In the original example, each scope has it’s own object, and so each is operating on their own object. If both scopes share the same object, then each is operating on the same object, and thus changes in one scope is reflected in the other.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply