angular.js - Angularjs如何建立 公共function
本文介绍了angular.js - Angularjs如何建立 公共function的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
我有两个function,需要在很多页面都有用到,如何将它们单独提出来放到一个js文件里面呢?
我看网上的信息大多都是建立一个service或者factory然后嵌入controller里面。但是我这两个function是在另一个function里面调用的。我试着把子controller放进function里就出错了,我要怎么做呢?有什么别的办法么?
我的代码类似于:
var app = angular.module('myApp', []);
app.controller('Ctrl', function($scope, $http) {
$scope.z = function{
$scope.word1 = 1;
$scope.word2 = 2;
$http.get(url, config)
.then(function (response) {
$scope.items = response.data.data;
$scope.a();
}
$scope.b= function{
$scope.a();
}
$scope.a= function{
}
}
});
其中function a和b是我需要提出来的公共function。word1,word2也是这两个function里面会用到的,但我不想把它们提出来,因为每个页面这两个值都是不一样的。目前这样的写法在我的页面上,功能都是可以实现的。要如何才能把这两个function放到一个单独的js文件里面呢?
解决方案
// app作为全局变量
window.app = angular.module('myApp', []);
// 下面这段提成一个单独的xxxCtrl.js文件
app.controller('Ctrl', [
'$scope',
'$http',
'yourService',
function($scope, $http, yourService) {
// a方法调用
yourService.a();
// b方法调用
yourService.b();
}
]);
// 下面这段提成一个单独的xxxService.js文件
app.factory('yourService', ['', function() {
// a,b公用方法
var temp = function() {
//...
};
function Service() {
this.a = function() {
temp();
//...
}
this.b = function() {
temp();
//...
}
}
return new Service();
}])
这篇关于angular.js - Angularjs如何建立 公共function的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文