簡體   English   中英

工廠angularjs中的訪問控制器作用域函數

[英]Access controller scope function in factory angularjs

我有一個控制器,還有一個使用該控制器功能的工廠。 之所以這樣做,是因為我想在更多的控制器中使用某些功能,具體取決於實際的$scope我的解決方案將是下面的代碼。 但是,角度拋出錯誤,指出controllerFunction未定義

編輯:此代碼有效! 我在代碼中的其他地方打了錯字。

angular.module('myApp')
 .controller('myController', function ($scope, $http, myInterface) {
    var myFactory = new myInterface($scope);
    $scope.controllerFunction = function(){
        // do something 
    }
 })
 .factory('myInterface', function(){
    var self;
    function Interface($scope) {
      this.$scope = $scope;
      self = this;
    }

    Interface.prototype.interfaceFunction = function(){
      self.$scope.controllerFunction(); 
    }
    return Interface;
});

您可以執行以下操作:代碼問題是您傳遞了$scope ,但是之后定義了函數。 注意: $scope is an object而不是單個共享的服務。 每個controller都有自己的$scope

var myApp = angular.module("myApp", []);
myApp.controller('Ctrl', function($scope, NameService) {

    $scope.callController = function(){console.log("Called controller")};
    $scope.NameService = new NameService($scope);     
});

myApp.factory('NameService', function() {

    //constructor
    function NameService(scope) {
        this._scope = scope;
        this._someFunction()
    }

    //wherever you'd reference the scope
    NameService.prototype._someFunction = function() {
        this._scope.callController();
    }

    return NameService;

});

http://fiddle.jshell.net/5gmnvL6b/

您需要從控制器將回調方法傳遞給工廠方法。

angular.module('myApp')
 .controller('myController', function ($scope, $http, myInterface) {
    myInterface.myMethod(function (){// callback method passed to factory
       $scope.controllerFunction();//will get called from factory via callback
   )}
    $scope.controllerFunction = function(){
        // do something 
    }
 })
 .factory('myInterface', function(){
     var myMethod = function (cb) {
        //your code
        cb();  //calling callback method of controller
     }

  return myMethod;

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM