angular.js - How to create public functions in Angularjs
我想大声告诉你
我想大声告诉你 2017-05-15 17:05:27
0
3
566

I have two functions that need to be used on many pages. How can I extract them separately and put them into a js file?
I see that most of the information on the Internet is to create a service or factory and then embed it in the controller. But my two functions are called inside another function. I tried to put the child controller into the function and an error occurred. What should I do? Is there any other way?
My code looks like:

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{   
   }          
}
});

Where functions a and b are the public functions I need to bring up. word1 and word2 are also used in these two functions, but I don't want to mention them because these two values ​​​​are different on each page. At present, this writing method can be implemented on my page. How can we put these two functions into a separate js file?

我想大声告诉你
我想大声告诉你

reply all(3)
phpcn_u1582
// 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();
}])
刘奇

It is still used as a service, passing word1, word2 and the like as parameters, which is flexible and reusable

为情所困

The public method can be extracted and put into the service, and then the service can be injected into the public method that needs to be called

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template