IT TIP

AngularJS 팩토리에서 $ scope에 액세스합니까?

itqueen 2020. 11. 27. 21:52
반응형

AngularJS 팩토리에서 $ scope에 액세스합니까?


저는 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있습니까?


일반적으로 $scope공장, 서비스 또는 공급자 내부에서는 사용하지 않습니다 . 일반적으로 promise(에 의해 반환 됨 $http)을 반환 한 다음 컨트롤러 (가있는 곳)에서 promise를 처리합니다 $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;
    });
}

나는 당신이 이것을 의미한다고 생각합니다.

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

다음 트릭은 매우 나쁜 습관이지만 서두르면 사용할 수 있습니다.

다음으로 교환 $scope:angular.element('[ng-controller=CtrlName]').scope()


개인적으로 나는 공장의 범위를 사용하고 싶기 때문에 모든 것을 옮기는 대신 factory.function ()을 호출하는 클라이언트의 매개 변수로 범위를 전달합니다.

또한 우리가 공장이나 서비스에서 직접 $ scope를 사용할 수 없기 때문에 $ scope.watch (...)를 사용하려고 할 때 이와 동일한 문제가 있었지만 이런 방식으로 작동하고 싶었 기 때문에 방금 업데이트했습니다. 함수는 범위를 매개 변수로 갖고 공장의 클라이언트가 $ 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>

도움이 되었기를 바랍니다. 문안 인사.


나는 이것이 가장 깨끗한 해결책이라고 생각합니다.

문제 나 개선 사항이 있으면 알려주십시오.

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

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

이 질문이 오래되었다는 것을 알고 있지만 이것이 저에게 효과적이었습니다.

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

});

참고 URL : https://stackoverflow.com/questions/22159189/accessing-scope-in-angularjs-factory

반응형