在工厂angularjs中访问控制器范围功能

时间:2016-10-22 17:05:42

标签: javascript angularjs

我有一个控制器和一个使用控制器功能的工厂。我这样做的原因是因为我想在更多控制器中使用某些功能,具体取决于实际的$scope 我的解决方案将是下面的代码。但是,angular会抛出错误,指出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;
});

2 个答案:

答案 0 :(得分:1)

您需要从控制器向您的工厂方法传递回调方法。

Char1_Label.removeTextField();

答案 1 :(得分: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/

相关问题