Accessing $scope in AngularJS factory?

前端 未结 7 1255
我寻月下人不归
我寻月下人不归 2020-11-27 13:11

I am new to AngularJS and find it very interesting, but I am a bit unclear about the following situation.

app.factory(\'deleteFac\', function($http){

var fa         


        
7条回答
  •  情书的邮戳
    2020-11-27 13:41

    Personally I would like to use scope from the factory, so, instead of moving all out I would pass the scope as parameter from the client which is calling to the factory.function().

    Also I was having this same issue when trying to use $scope.watch(...) since we cannot use directly $scope from factories or services but I wanted to have this working in this way, so that is why I just updated my function to have scope as parameter and let the factory's client to send the $scope. So, this would be my solution:

    var app = angular.module("myApp", []);
    
    app.factory('MyFactory', function($http) {
    
          var factory = {};
          //This is only for my own issue I faced.
          factory.Images = {};
    
          factory.myFunction = function(id, scope) {
            //This is an example of how we would use scope inside a factory definition
            scope.details = "Initial Value";
            //In my case I was having this issue while using watch
            scope.$watch('details' , function(newValue, oldValue) {
              if(oldValue){
                 scope.log = "Details was updated to : " +newValue;
                }
            });
            
            scope.details = "My Id is: "+id;
           };
            return factory;
    });
    
    //Controller: Factory's Client.
    app.controller("MyController", ['$scope', 'MyFactory', function($scope, MyFactory) {
      
            MyFactory.myFunction(5, $scope);
    }]);
    
    
    {{details}}

    {{log}}

    I hope this can help. Regards.

提交回复
热议问题