在AngularJS工厂中访问$ scope?

时间:2014-03-03 22:46:30

标签: javascript angularjs

我是AngularJS的新手,发现它非常有趣,但我对以下情况有点不清楚。

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

var factory = {}; 

factory.edit = function(id){
  $http.get('?controller=store&action=getDetail&id=' + id).
    success(function(data, status){
        /** 
        got an error on the following 
        when i use return data; and i get data undefined 
        in the controller which i get it because its doing a ajax call
        you don't get data until the call first.
        **/
        $scope.detail = data;
      })
    }

return factory;
})

当我分配给$scope并使用返回数据时,我收到错误,无论如何,我是否可以将返回数据分配给$scope

7 个答案:

答案 0 :(得分:78)

您通常不会在工厂,服务或提供商中使用$scope。通常,您将返回promise(由$http返回),然后在控制器中处理承诺(您拥有$scope)。

factory.edit = function(id){
    return $http.get('?controller=store&action=getDetail&id=' + id);
}

控制器功能:

$scope.edit = function(id) {

    deleteFac.edit(id).then(function(response) {
        $scope.something = response.model;
    });
}

答案 1 :(得分:13)

我猜你的意思是:

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

  var service = {}; 

   factory.edit = function(id, success, error){
        var promise = $http.get('?controller=store&action=getDetail&id=' + id);
        if(success)
           promise.success(success);
        if(error)
           promise.error(error);
   };

   return service;
});

然后在您的控制器中执行:

function MyController($scope, deleteFac){
   deleteFac.edit($scope.id, function(data){
       //here you have access to your scope.
   });
}

答案 2 :(得分:8)

以下技巧是一种非常糟糕的做法,但如果您赶时间,可以使用它:

$scopeangular.element('[ng-controller=CtrlName]').scope()

交换

答案 3 :(得分:4)

我个人想要使用工厂中的作用域,因此,我不会全部移出,而是将作为参数的作用域传递给调用factory.function()的客户端。

在尝试使用$ scope.watch(...)时我也遇到了同样的问题,因为我们不能直接使用工厂或服务的$ scope,但我希望这样工作,所以这就是为什么我刚刚更新了我的函数,将范围作为参数,让工厂的客户端发送$ scope。所以,这将是我的解决方案:



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

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyController">
  <span>{{details}} </span>
  <hr>
  <p>{{log}} </p>
</div>
&#13;
&#13;
&#13;

我希望这可以提供帮助。 问候。

答案 4 :(得分:1)

我认为这是最干净的解决方案:

如果有问题或改进,请告诉我。

(function(){
  angular.controller('controllerName', controllerName);
  controllerName.$inject = ['$scope', factory];

  function controllerName($scope, factory){
    var vm = this;

    vm.data = factory.alertPopup();
  }

  angular.factory('factory', factory);
  factory.$inject = ['externalServices'];

  function factory(externalServices){
    return {
      returnData : returnData
    }

    function returnData(){
      return externalServices.whatever();
    }
  }
})();

答案 5 :(得分:0)

.factory('POPUP', function($ionicLoading, $ionicPopup) {
  var self = this;
  // THIS BLOCK SCREEN ! for loading ! Be carefoull !! ( deprecated: assign this to a var for security)
  self.showLoading = function(title, message, scope){
  scope.loading = true;
  return $ionicLoading.show({ content: message, showBackdrop: false });
  };
  self.hideLoading = function(title, message, scope){
  scope.loading = false;
  return $ionicLoading.hide();
};

// NOT BLOCK SCREEN- SIMPLE ALERTS - Standards popups
self.showAlert = function(title, message, callback){
  var alertPopup = $ionicPopup.alert({ title: title, template: message });
  alertPopup.then(function(res) {
      console.log('callback popup');
      if (callback){ callback(); }
  });
};
 self.showConfirm = function(objectPopup, callback){
 if (objectPopup === undefined){ objectPopup = { title: 'test confirm    Popup', template: 'Message test Confirm POPUP' }; }
 var alertPopup = $ionicPopup.confirm(objectPopup);
 alertPopup.then(function(res) {
   if (res) { callback(true); }
    else { callback(false); }
 });
 };
   return self;
   }) 

答案 6 :(得分:0)

我知道这个问题已经过时了,但这对我有用了

app.factory('myFactory',function(){

    let toRet = {
        foo: foo
    }

    return toRet;

    function foo(){ // This function needs to use passed scope.
        let $scope = toRet.$scope;
        // Do stuff with $scope.
    }
});

app.controller('myController',function($scope,myFactory){

    myFactory.$scope = $scope;
    /*
        We could just pass $scope as a parameter to foo, but this is
        for cases where for whatever reason, you cannot do this.
    */
    myFactory.foo();

});