2015-10-15 95 views
0

我有2个控制器。如何避免在angularjs冗余变量

第一个是listController.js:

app.controller('listCtrl', function($scope, $http, $controller, $window) { 
    $scope.user = [{id:1,name:'rina'},{id:2,name:'anna'},{id:3,name:'yuna'}]; 
}); 

,第二个是editController.js

app.controller('editCtrl', function($scope, $http, $controller, $window) { 
    $scope.user = [{id:1,name:'rina'},{id:2,name:'anna'},{id:3,name:'yuna'}]; 
}); 

正如u能看到。我在两个控制器中都使用了变量$scope.user。现在我想用它一次。我的意思是我想避免冗余代码。我如何在我的任何控制器中调用该变量。有什么建议么?

回答

2

您可以添加一个服务,它将负责提供数据。

app.service('UsersService', function() { 
    this.getUsers = function() { 
     return [{id:1,name:'rina'},{id:2,name:'anna'},{id:3,name:'yuna'}]; 
    } 
}); 

然后在你的控制器,你可以把它像这样:

app.controller('listCtrl', function($scope, $http, $controller, $window, UsersService) { 
    $scope.user = UsersService.getUsers(); 
});