Tuesday 15 May 2012

javascript - What is the best practice in sharing a scope variable among controllers? -



javascript - What is the best practice in sharing a scope variable among controllers? -

i have array of variables (i'll phone call arrvar) available controllers through service. variable has been assigned scope variable in ctrla $scope.arrvar. if user toggles button under ctrla, method attached ctrla create changes $scope.arrvar, update variable in service, , nowadays list using ng-repeat.

but have totally separate controller, ctrlb, needs create changes scope variable under ctrla, not available access ctrlb.

i can think of 2 solutions:

a global controller assign variable @ root scope

but both approaches don't seem best practise. there other elegant way of doing it? 2 controllers totally different, merging won't it.

if share info specific obj (like element position data.msg) bind service no watching or anything.

2 controllers plunker

app.controller('firstctrl', function($scope, shared) { $scope.data = shared; }) .controller('secondctrl', function($scope, shared) { $scope.data = shared; }) .factory('shared', function() { homecoming { msg : ['one','two','three'] } }); <div ng-controller="firstctrl"> <input ng-model="data.msg"/> {{data}} </div> <div ng-controller="secondctrl"> <input ng-model="data.msg"/> {{data}} </div>

javascript angularjs

No comments:

Post a Comment