AngularJS models, multiple $ scopes and two-way data binding

I like the fact that AngularJS does not require any special syntax for models, but there is one scenario that I seem to be unable to wrap around. Take the following

My data The service wraps every taste of the data warehouse that I use:

app.factory('dataService', function() {
    var data = 'Foo Bar';

    return {
        getData: function() {
            return data;
        }
    };
});

I have two controllers that access the same piece of data:

app.controller('display', function($scope, dataService) {
    $scope.data = dataService.getData();
});

app.controller('editor', function($scope, dataService) {
    $scope.data = dataService.getData();
});

If I have two views, one of which changes data, why the other update is not updated automatically?

<div ng-controller="display">
<p>{{data}}</p>
</div>

<div ng-controller="editor">
<input type="text" value="{{data}}"/>
</div>

I understand how this works in something like Knockout, where I am forced to knock out the data of an observable object. Thus, any changes in one part of the application trigger subscriptions and update views in another. But I'm not sure how to do this in Angular.

Any tips?

+5
2

, , .

HTML

<div ng-controller="display">
  <p>{{data.message}}</p>
</div>

<div ng-controller="editor">
  <input type="text" ng-model="data.message"/>
</div>

Script

app.factory('dataService', function() {
    var data = {message: 'Foo Bar'};

    return {
        getData: function() {
            return data;
        }
    };
});

: Fiddle

+6

, , , - , . angular, . .

data. data , . , dataService , , . dataService model {data: data} model.data data.

, , , angular .

+1

All Articles