0

How the values of obj returned in the factory can access the Local variables or functions. Suppose i want to encapsulate my model as local variable or function in the factory or service but i want to return them as values of return object. But when i'm doing so i getting an error saying that variable not defined.Can any one help me on this problem.

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)}
   });

gives an error

4

1 に答える 1

0

これは私がそれを行う方法です。これは、友達をリストして追加する方法の簡単な例です。コードペンで見る

<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>
于 2016-03-22T21:06:56.867 に答える