angular.js - Angularjs如何建立 公共function

浏览:28日期:2023-01-04

问题描述

我有两个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文件里面呢?

问题解答

回答1:

// 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();}])回答2:

还是作为一个sevice,将word1,word2之类的作为参数传进去,灵活可复用

回答3:

公共方法可以提取出来放到service中,再在需要调用该公共方法中注入service,就可以咯

相关文章: