Tuesday, 15 July 2014

javascript - Sharing data with between Controllers with a Factory, AngularJS -



javascript - Sharing data with between Controllers with a Factory, AngularJS -

i want share info between controllers:

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.4/angular.min.js"></script> <script> var myapp = angular.module('myapp',[]); myapp.factory('data', function(){ homecoming {show: true, text: "hello"}; }); myapp.controller('ctrl1', ['$scope', 'data', function($scope, data) { $scope.data = data; }]); myapp.controller('ctrl2', ['$scope', 'data', function($scope, data) { $scope.click = function(){ info = {text:"hello2", show:true}; } }]); </script> <body ng-app='myapp'> <div style="background-color:red;margin-top:30px;" ng-controller="ctrl1"> {{data.text}} </div> <div style="background-color:yellow;margin-top:30px;" ng-click="click()" ng-controller="ctrl2"> click alter info </div> </body>

demo http://plnkr.co/edit/qhuwlyjbqdvl20fl7eeu?p=preview . doesn't work, if write

data.text = 'hello2'; data.show = true;

it works perfectly. demo http://plnkr.co/edit/xktlulbu0dqpusincryc?p=preview

it handy updating model specifying json, how can it?

by doing data = {text:"hello2", show:true}; overwrite initial data object, results broken reference. that's why can't assign new object. can this:

myapp.factory('data', function(){ homecoming { prop: {show: true, text: "hello"} }; });

and later:

data.prop = {text: "hello2", show: true};

javascript angularjs

No comments:

Post a Comment