Issue
I already have a code with 2 separate controllers .
Each controller's scope/view has an input text
and a span
.
All fine.
But Looking at the line with yellow color label(empty at the moment) - which is found within the second controller , I want the value to be the same value from as in first controller .
so I'm expecting the line to be (and changed automatically) :
Value from the FirstController is :First Cntrl
I already know that I need a serivce :
so here is my code :
angular.module('app', [])
.controller("FirstCtrl", ['$rootScope', '$scope', 'myservice', function($rootScope, $scope, myservice)
{
myservice.messageFromCntrl1= this.message;
this.message = "First Cntrl";
}]).controller("SecondCtrl", ['$rootScope', '$scope', 'myservice', function($rootScope, $scope, myservice)
{
this.message = "Second Cntrl";
this.messageFromCntrl1 = myservice.messageFromCntrl1;
}])
.service('myservice', function()
{
this.messageFromCntrl1 = "???";
});
In the first controller I do set
myservice.messageFromCntrl1= this.message;
And in the second controller I do read :
this.messageFromCntrl1 = myservice.messageFromCntrl1;
And in the HTML :
Value from the FirstController is :<span style='color:red;'>{{myservice.messageFromCntrl1}}
But it doesn't work. What am I missing?
Solution
I modified your JSBIN, check it here. I believe it behaves now as you want it to.
angular.module('app', [])
.controller("FirstCtrl", ['$rootScope', '$scope', 'myservice', function($rootScope, $scope, myservice)
{
this.message = myservice.messageFromCntrl1;
this.message.data = "First Cntrl";
}]).controller("SecondCtrl", ['$rootScope', '$scope', 'myservice', function($rootScope, $scope, myservice)
{
this.message = "Second Cntrl";
this.messageFromCntrl1 = myservice.messageFromCntrl1;
}])
.service('myservice', function()
{
this.messageFromCntrl1 = {data:""};
});
And in your view
<div ng-controller="FirstCtrl as first">
<input type="text" ng-model="first.message.data">
<h1>{{first.message.data}}</h1>
</div>
<div ng-controller="SecondCtrl as second">
<input type="text" ng-model="second.message">
<h1>{{second.message}} </h1>
Value from the FirstController is:
<span style='color:red;'>{{second.messageFromCntrl1.data}}</span>
</div>
First of all, if you want to keep this value updated between controllers you need to use objects and not simple variables. With objects you operate on references and updates are shared between all references of object.
Second, you tried to access service directly in view. You need to bind service reference to controller's scope.
Answered By - JacobMiki
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.