.factory('userService',()){ var user = {}; return { getFirstname : function () { return user.firstname; }, setFirstname : function (firstname) { user.firstname = firstname; } }
And I'm using this service in my two controllers MainCtrl and AccountEditCtrl I'm using my getFirstname() in my MainCtrl and setFirstname in AccountEditCtrl
Now, according to Angular's doc, whenever the return value from a function call changes, Angular will update the values in the view.
回答5:
sample factory with getter and setter example code
Input is : {{data.firstName}}
Input should also be here: {{data.firstName}}
var myApp = angular.module('myApp', []); myApp.factory('Data', function(){ var service = { FirstName: '', setFirstName: function(name) { // this is the trick to sync the data // so no need for a $watch function // call this from anywhere when you need to update FirstName angular.copy(name, service.FirstName); } }; return service; }); // Step 1 Controller myApp.controller('FirstCtrl', function( $scope, Data ){ $scope.setData = function() { Data.FirstName='Tridip'; }; }); // Step 2 Controller myApp.controller('SecondCtrl', function( $scope, Data ){ $scope.FirstName = Data.FirstName; $scope.getData = function() { alert('get data '+Data.FirstName) }; });