Communication between controllers in AngularJS

I will learn how to share data between controllers, but I am facing some problems.

I have this html view:

<div ng-app="MyApp">
    <div ng-controller="firstCtrl">
        <input type="text" ng-model="data.message"/>    
        {{data.message}} 
    </div>
    <div ng-controller="secondCtrl">
        <input type="text" ng-model="data.message"/>    
        {{data.message}}    
    </div>
    <div ng-controller="thirdCtrl">
        <input type="text" ng-model="data.message"/>    
        {{dataTwo.messageTwo}}
    </div>  
</div>  

My script looks like this:

var myApp = angular.module("MyApp",[]);

myApp.service("Data", function() {
    return {
        message : "Hello World",
    }
 });

function firstCtrl($scope, Data) {
    $scope.data = Data; 
};

function secondCtrl($scope, Data) {
    $scope.data = Data;     
};

function thirdCtrl($scope, Data) {

    $scope.data = Data; 
    $scope.dataTwo = {
        messageTwo : $scope.data.message    
    };

};

I connect my controllers using the "Service". Everything works well, but in the third controllers "dataTwo.messageTwo" does not change when I pass the new value to the input field. The value of dataTwo.messageTwoi is all the time ("Hello World").

What am I doing wrong?

+4
source share
5 answers

dataTwo.messageTwo $scope.data.message. . .
DataTwo, : ng-model="dataTwo.messageTwo".

+4

ng-

<div ng-controller="thirdCtrl">
    <input type="text" ng-model="dataTwo.messageTwo"/>    
    {{dataTwo.messageTwo}}
</div>  
+2

$watch :

function thirdCtrl($scope, Data) {

    $scope.data = Data; 

    $scope.dataTwo = {
        messageTwo : $scope.data.message
    };

    $scope.$watch('data.message', function (message)
    {
        $scope.dataTwo.messageTwo = message;
    });

};

$watch, , , -.

+2

messageTwo : $scope.data.message, , messageTwo. , $scope.data messageTwo. messageTwo, .

$scope.watch('data.message',  function (newValue, oldValue) {
  $scope.dataTwo.messageTwo = newValue;
}
+1

$watch, data.message dataTwo.messageTwo ngModel. ES5 defineProperty:

$scope.dataTwo = {};

Object.defineProperty($scope.dataTwo, 'messageTwo', {
    get: function() {
        return $scope.data.message;
    }
});

: http://plnkr.co/edit/2BRJNzOyfVxrAqIS0dXs?p=preview

: defineProperty IE9 +.

+1

All Articles