AngularJs将控制器的值发送给服务

时间:2014-07-29 19:16:02

标签: angularjs web-services factory

问题很简单,我在控制器中有价值,我想将此值发送给另一个控制器。

我有这段代码:

var app = angular.module("MyApp", []);

app.factory("UserService", function() {
  var users = //how to get the value user of MyCtrl ?

  return {
    all: function() {
      return users;
    },
    first: function() {
      return users[0];
    }
  };
});

app.controller("MyCtrl", function($scope, UserService) {
  var users = ["Peter", "Daniel", "Nina"];
  $scope.users = UserService.all();
});

app.controller("AnotherCtrl", function($scope, UserService) {
  $scope.firstUser = UserService.first();
});

我不知道如何从var users = ["Peter", "Daniel", "Nina"];中的控制器MyCtrl获取UserService的值?

现场例证:http://jsbin.com/vacutodo/1/edit?html,js,output

1 个答案:

答案 0 :(得分:0)

您可以将其注入您的函数:

app.factory('UserService', ['MyCtrl', function(MyCtrl) {
    var users = MyCtrl.users;
    ...
};

app.controller("MyCtrl", function($scope, UserService) {
    var users = ["Peter", "Daniel", "Nina"];
    $scope.users = UserService.all();

    return {
        users: users
    };
});