2017-02-09 87 views
0

我想创建一个基本控制器,我可以使用所有其他控制器需要在一起的函数。我想继承或实例化我的低级控制器上的JavaScript页面。在子控制器中调用父控制器

我在网上看,看到不同的建议,但它没有为我工作。我已经把2个脚本按顺序放在布局上。我创建了一个基本的控制器:

var app = angular.module('mainApp', []); 

我试图访问它诠释,他的另一个控制器:

baseController.app 
    .controller('listsController'..... 

我如何获得访问baseController(这将在未来拥有的功能)在我listController文件?

回答

2

一种方法是使用$controller服务实例像this回答状态

app.controller('ChildCtrl', function($scope, $controller) { 
    $controller('ParentCtrl', {$scope: $scope}); 
}); 

但正如你说,你有所有其他控制器的需要,我建议你创建一个服务,将功能改为保留这些常用功能。

下面是一个服务例如:

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

    var function1 = function(){ 
     //Do your thing 
    }; 

    var function2 = function(){ 
     //Do your thing 
    }; 

    return { 
     function1: function1, 
     function2: function2 
    } 
}); 

然后,在其中需要使用常用功能控制器注入服务

app.controller('ChildCtrl', ['$scope', 'functionServ', 
    function ($scope, functionServ) { 

    //Call the functions like: functionServ.function1(); 
}]); 
相关问题