13

私はangularjsサービス内に関数を書きたいのですが、それをすべてのサービスで再利用したいです。

コントローラー。

var mod= angular.module('myapp', ['eventFilters', 'highlight', 'event', 'dayfilter', 'Services']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
      when('/', {templateUrl: 'template.html',   controller: Ctrl}).
      when('/temp', {templateUrl: 'temp.html',   controller: tempCtrl}).
      otherwise({redirectTo: '/invalid'});
}]);
mod.service ('sharedService', function() {
function daysInMonth(month,year) {
    return new Date(year, month+1,0).getDate();
}
});

コントローラーのいずれかでdaysInMonth関数を使用したい。出来ますか?もしそうなら、誰かがフィドルのいくつかの例で私を簡単に説明できますか?

前もって感謝します

4

6 に答える 6

26

これは、コントローラーでサービスを使用(注入)する方法の基本的な例をいじくりまわしたものです。

http://jsfiddle.net/uhmNR/1/

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


//Here is the service Users with its functions and attributes
//You can inject it in any controller, service is a singleton and its data persist between controllers
myApp.factory('Users', function () {

    var userName = "John Doe";

    return {
        getUserName: function () {
             return userName;                   
        },
        setUserName: function (newName) {
            userName = newName;
        }
    }
});

//An Util service with DaysInMonth method   
myApp.factory('Util', function () {

    return {
        daysInMonth: function (month,year) {

            return new Date(year, month+1,0).getDate();
        }
    };

});   

//Here I am injecting the User service andusing its methods   
myApp.controller('MyCtrl', ['$scope', 'Users', 'Util', function ($scope, Users, Util) {

    Users.setUserName('Robin Hood');

    $scope.name = Users.getUserName();

    //Using Util.daysInMonth()
    $scope.date = Util.daysInMonth(12,2012);
}]);

それが役に立てば幸い。

于 2012-12-19T12:46:07.737 に答える
6

関数をサービスとして公開し、AngularJSインジェクターに残りを任せます。daysInMonthモジュールでサービスを静的な値として簡単に設定できます。http://jsfiddle.net/hbulhoes/zdtnw/でこれを実際に見てください

var mod = angular.module('myapp', []);

// This is the declaration of the daysInMonth service. It's set as
// a value in the module, with the value being the very function
// you want to share among other services and controllers:
mod.value('daysInMonth', function(month, year) {
    return new Date(year, month+1,0).getDate();
});

// And this is an example controller that depends on the daysInMonth function.
function MyController($scope, daysInMonth){
    $scope.DaysInCurrentMonth = daysInMonth(12, 2012);
}
于 2012-12-19T13:02:02.723 に答える
1

あなたはそれを公開する必要があります。リターンブロックでラップします。

var mod= angular.module('myapp', ['eventFilters', 'highlight', 'event', 'dayfilter', 'Services']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
  when('/', {templateUrl: 'template.html',   controller: Ctrl}).
  when('/temp', {templateUrl: 'temp.html',   controller: tempCtrl}).
  otherwise({redirectTo: '/invalid'});
}]);
mod.service ('sharedService', function() {
   return {
      daysInMonth: function(month,year) {
         return new Date(year, month+1,0).getDate();
      }
   };
});
于 2012-12-20T08:19:25.103 に答える
1

すべてのコントローラーで関数を使用できるようにする場合は、サービスを使用する代わりに、$rootScopeでメソッドを定義することを検討してください。

myApp.run(function($rootScope) {
    $rootScope.daysInMonth = function(year, month) {
        return new Date(year, month+1,0).getDate();
    }
});

次に、プロトタイプスコープの継承により、すべてのコントローラーのスコープがメソッドにアクセスできるようになります(依存性注入は必要ありません)。次のような任意のコントローラーで呼び出すことができます。

function MyCtrl($scope) {
   console.log($scope.daysInMonth(12, 2012));
}​

JavaScriptは$scopeで定義された関数daysInMonthを検出しないため、親スコープ(この場合はルートスコープ)で関数を検索し、それを検出します。

于 2012-12-19T16:28:52.327 に答える
0

実際のAngularサービス(ファクトリやプロバイダーではない)を使用する場合は、Angularの方法で何かを作成するために次のことを行う必要があります。

mod.service ('sharedService', function() {
  function daysInMonth(month,year) {
    return new Date(year, month+1,0).getDate();
  }
});

// Would turn into 

mod.service("sharedService", function(){
  this.daysInMonth(month, year){
    return new Date(year, month + 1, 0).getDate();
  }
});

サービスがNEW'EDのときに作成されるデフォルトのこのオブジェクトをオーバーライドする必要がない限り、サービスから戻ることはできませ。その場合、オブジェクトリテラル、関数定義、配列、プリミティブを除くほとんどのオブジェクトを返すことができます。「なぜデフォルトの動作をオーバーライドする必要があるのですか?」という質問をすることを忘れないでください。

それがサービスの要点です。SERVICE Angularを注入すると、渡した関数がNEWになり、説明されているように関数が返されます。あなたの場合、サービスはまさにあなたが必要とするものになります。Angularはサービスを1回だけビルドし、新しいsharedService関数の結果はアプリケーション全体で利用できますが、サービスがアプリケーションのどこかで少なくとも1回DIされた場合に限ります。DIを行わないと、サービスが遅延ロードされるため(ファクトリとサービス)、サービスが作成されることはありません。

本当に何かを返品したい場合は(サービスでそれを行うことはできますが)、適切な場所はAngularFactoryになります。実際、ファクトリーから戻らない場合は、ちょっとした通知が届きます

エラー: プロバイダー'sharedService'は$getファクトリメソッドから値を返す必要があります。

注:ここで、$get関数はサービス関数定義の2番目の引数です。

mod.factory("sharedService", function(){
  function daysInMonth(month, year){
    return new Date(year, month + 1, 0).getDate();
  }

  return {
    daysInMonth: daysInMonth
  }

  // Or you could do this...
  return daysInMonth;
});

Angular Factoryを使用すると、 NEW'ED関数を取得できなくなります。そのため、リターンを作成する必要があります。

于 2016-11-21T16:37:57.930 に答える
0

OPは、サービスが、たとえば$timeout関数のような関数であることを意味していると思います。デフォルトのサービスファクトリは、返されるものすべての「サービス」を作成するため、次のように実行できます。

angular.module('myApp.myModule',[])
.factory('add',['$injectables',function($injectables) {
  return function(arg1,arg2)
  {
    //this is the function that will be called when you use this service
    return arg1 + arg2;
  }
}]);

使用法:

angular.module('myApp.Othermodule',['myApp.myModule'])
.controller('controllername',['add',function(add) {

  //controller code and somehwere
  $scope.z = add($scope.x,$scope,y);
}]);

于 2017-09-12T18:34:31.837 に答える