工厂服务返回对象

时间:2016-03-22 20:31:35

标签: javascript angularjs factories

工厂中返回的obj值如何访问Local变量或函数。假设我想将我的模型封装为工厂或服务中的局部变量或函数,但我想将它们作为返回对象的值返回。但是,当我这样做时,我得到一个错误,说明变量没有定义。任何人都可以帮我解决这个问题。

app.factory('myFactory',function(){
  var listofFriends=["john","ajay",.....];
  var addFriend=function(name){
         if(name!==""){
          listofFriends.push(name);
            };
         return listofFriends;};
   return{Friends:listofFriends,addfriend:addFriend(name)}
   });

给出错误

1 个答案:

答案 0 :(得分:0)

我就是这样做的。这是一个如何列出和添加朋友的简单示例。 See it on codepen

<script src="https://code.angularjs.org/1.4.9/angular.min.js"></script>

<div ng-app="myApp" ng-controller="MyController">
  my friends: {{friends}} <br>
  <input ng-model="newFriendName" type="text" />
  <button ng-click="addNewFriend(newFriendName)">Add</button>
</div>

<script>
  var app = angular.module('myApp', []);

  app.factory("myService", function(){
    var serviceObject = {};
    var listOfFriends = ["john","ajay","amy"];

    serviceObject.getFriends = function(){ return listOfFriends; }
    serviceObject.addFriend = function(name){ if (name) listOfFriends.push(name) };

    return serviceObject;
  });

  app.controller("MyController", ["$scope", "myService", function($scope, myService){
    $scope.friends = myService.getFriends();
    $scope.newFriendName = "";

    $scope.addNewFriend = function(name){
      myService.addFriend(name);
      $scope.friends = myService.getFriends();
    }
  }]);
</script>