Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing data between controllers in AngularJS

Tags:

angularjs

I learn how sharing data between controllers, but I encounter some problem.

I have such 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 look 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 by using "Service". Everything work good but in third controllers "dataTwo.messageTwo" not changing when I passing new value to input field.Value of dataTwo.messageTwoi is the whole time same ("Hello World").

What I doing wrong?

like image 741
dejmien25 Avatar asked Dec 25 '22 04:12

dejmien25


1 Answers

dataTwo.messageTwo is not binded to $scope.data.message. it just get its value once during creation of the controller. so it is not possible to do binding that way.
If you want dataTwo to be changed you need to define it in the input model like this: ng-model="dataTwo.messageTwo".

like image 74
oshai Avatar answered Dec 28 '22 07:12

oshai