2016-10-22 95 views
2

我有一個控制器和一個使用控制器功能的工廠。我這樣做的原因是因爲我想在更多控制器中使用一些功能,具體取決於實際情況$scope 我的解決方案與以下代碼相似。然而,角拋出一個錯誤,說controllerFunction是undefined工廠中的訪問控制器作用域函數angularjs

編輯:此代碼正在工作!我在代碼中的其他地方犯了一個錯字。

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

,您可以移動'controllerFunction()'函數將一個特定的服務..比你可以在任何地方使用它 –

+0

你想從你的工廠調用$ scope.controllerFunction? – Ved

+0

@Ved是的,我試着打電話給它。 –

回答

1

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

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; 

}); 
1

你可以做這樣的事情,你的代碼的問題是你逝去的$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/

相關問題