问题描述
我想使用Angularjs模块中另一个Controller的另一种方法.我有两个名称为Controller的控制器: bookApp 模块中的 Booklist 控制器.另一个名为 ShowEachBook .在 Booklist 控制器中,创建 ViewItem()方法,该方法可从 ShowEachBook 控制器中的 View_A_book()方法访问.
I want to use another method from another Controller in an Angularjs Module.I have two Controller one named: Booklist Controller in bookApp Module.and another one named ShowEachBook.In Booklist Controller I create ViewItem() method which can be accessible from View_A_book() method in ShowEachBook Controller.
这是我在BookApp模块中的控制器
Here is my Controller in BookApp module
var bookApp = angular.module('bookApp', []);
bookApp.controller('bookListCtr', function ($scope, $http) {
$scope.ViewItems = function ($id) {
$this->View_A_book($id);// This is example because I want to used View_A_book() method here
};
})
这是 ShowEachBook 控制器
bookApp.controller('ShowEachBook', function ($scope, $http) {
$scope.View_A_book = function($id){
/// get book from server.
}
})
推荐答案
创建工厂.您只需要定义一次,就可以从任何控制器中注入和调用它. 看到这个文章.
Create a factory.You only have to define it once, and it can be injected and called from any controller. See this article.
-
制造一个工厂ViewBook
,并向其中添加您的功能:您的工厂:
Make a factory ViewBook
, and add your function to it:Your factory:
angular.module('bookApp')
.factory('ViewBook', function () {
return {
view_a_book: function(id) {
//do whatever you want to.
return something
},
};
});
您的控制器:
var bookApp = angular.module('bookApp', []);
bookApp.controller('bookListCtr', function ($scope, $http, ViewBook) {
$scope.ViewItems = function ($id) {
ViewBook.view_a_book($id);
};
})
使用$scope
和$http
添加对工厂的引用,然后使用该引用进行调用.可以对您拥有的任何控制器重复此操作.
You add a reference to the factory with $scope
and $http
, and use that to call it. This can be repeated for any controllers you have.
这篇关于如何从AngularJs中的另一个控制器访问控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!