如何添加一些小工具功能,以我的AngularJS应用程序? [英] How can I add some small utility functions to my AngularJS application?

查看:187
本文介绍了如何添加一些小工具功能,以我的AngularJS应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一些实用功能添加到我的AngularJS应用。例如:

I would like to add some utility functions to my AngularJS application. For example:

$scope.isNotString = function (str) {
    return (typeof str !== "string");
}

时要做到这一点,将其添加为服务的最佳方式?从我读我可以做
这一点,但后来我想在我的HTML页面使用这些所以它仍然是可能的,如果
它们是在服务?例如,我可以使用以下命令:

Is the best way to do this to add them as a service? From what I have read I can do this but then I would like to use these in my HTML pages so is it still possible if they are in a service? For example can I use the following:

 <button data-ng-click="doSomething()"
         data-ng-disabled="isNotString(abc)">Do Something
 </button>

有人可以给我的,我怎么能添加这些例子。我应该创建一个服务
还是有做一些其他的方式。最重要的是我想这些实用工具
在文件中,而不是功能结合主设立的另一部分。

Can someone give me an example of how I could add these. Should I create a service or is there some other way of doing it. Most important I would like these utility functions in a file and not combined with another part of the main set up.

据我所知有一些解决方案,但他们都不是很清楚。

I understand there's a few solutions but none of them are so clear.

解决方案1 ​​ - 由城市提案

$scope.doSomething = ServiceName.functionName;

这里的问题是我有20个功能和十个控制器。如果我这样做,这将意味着加入了大量的code到每个控制器。

The problem here is I have 20 functions and ten controllers. If I did this it would mean adding a lot of code to each controller.

解决方案2 - 我所提出

    var factory = {

        Setup: function ($scope) {

            $scope.isNotString = function (str) {
                return (typeof str !== "string");
            }

这样做的缺点是,在每一个控制器的开始我将有一个或多个这些设置的调用哪些通过$范围内的每个服务

The disadvantage of this is that at the start of every controller I would have one or more of these Setup calls to each service which passed the $scope.

解决方案3 - 由城市提案

按城市创建一个通用服务看起来不错的提出的解决方案。这里是我的主要设立:

The solution proposed by urban of creating a generic service looks good. Here's my main set up:

var app = angular
    .module('app', ['ngAnimate', 'ui.router', 'admin', 'home', 'questions', 'ngResource', 'LocalStorageModule'])
    .config(['$locationProvider', '$sceProvider', '$stateProvider',
        function ($locationProvider, $sceProvider, $stateProvider) {

            $sceProvider.enabled(false);
            $locationProvider.html5Mode(true);

我要补充的通用服务,以这一点,我怎么能这样做呢?

Should I add the generic service to this and how could I do it ?

推荐答案

修改15年7月1日:

我写了前这个回答pretty很长一段时间,并没有被跟上了很多棱角了一段时间,但是好像这个答案还是比较受欢迎的,所以我想指出的是,一夫妇点@nicolas使得下面都不错。其一,注入$ rootScope和附加助理会有让你不必添加它们每一个控制器。此外 - 我同意,如果您要添加什么应该被认为是角的服务或过滤器,它们应该被采纳到该方式code。

I wrote this answer a pretty long time ago and haven't been keeping up a lot with angular for a while, but it seems as though this answer is still relatively popular, so I wanted to point out that a couple of the point @nicolas makes below are good. For one, injecting $rootScope and attaching the helpers there will keep you from having to add them for every controller. Also - I agree that if what you're adding should be thought of as Angular services OR filters, they should be adopted into the code in that manner.

此外,由于当前版本1.4.2,角暴露了一个提供者的API,它允许被注入到配置块。看到这些资源更多:

Also, as of the current version 1.4.2, Angular exposes a "Provider" API, which is allowed to be injected into config blocks. See these resources for more:

<一个href=\"https://docs.angularjs.org/guide/module#module-loading-dependencies\">https://docs.angularjs.org/guide/module#module-loading-dependencies

<一个href=\"http://stackoverflow.com/questions/12903338/angularjs-dependency-injection-of-value-inside-of-module-config\">AngularJS里面的值依赖注入module.config

我不认为我会更新低于实际code块,因为我真的不积极采用了棱角分明的这些天,我真的不希望冒险新的答案没有感觉舒服,它实际上是符合新的最佳实践。如果别人觉得到它,通过各种手段去了。

I don't think I'm going to update the actual code blocks below, because I'm not really actively using Angular these days and I don't really want to hazard a new answer without feeling comfortable that it's actually conforming to new best practices. If someone else feels up to it, by all means go for it.

编辑14年2月3日:

想着这和阅读一些其他的答案后,其实我觉得我preFER由@Brent沃什伯恩和@Amogh Talpallikar提出了该方法的变化。特别是如果你正在寻找像isNotString()或类似工具。这里的一个明显优势就是可以重新使用它们的角code之外,你可以使用它们的配置功能(你不能做的服务)的内部。

After thinking about this and reading some of the other answers, I actually think I prefer a variation of the method brought up by @Brent Washburne and @Amogh Talpallikar. Especially if you're looking for utilities like isNotString() or similar. One of the clear advantages here is that you can re-use them outside of your angular code and you can use them inside of your config function (which you can't do with services).

话虽这么说,如果你正在寻找一种通用的方式重新利用什么应该适当地服务,老答案,我认为仍然是一个很好的一个。

That being said, if you're looking for a generic way to re-use what should properly be services, the old answer I think is still a good one.

我现在会做的是:

app.js:

var MyNamespace = MyNamespace || {};

 MyNamespace.helpers = {
   isNotString: function(str) {
     return (typeof str !== "string");
   }
 };

 angular.module('app', ['app.controllers', 'app.services']).                             
   config(['$routeProvider', function($routeProvider) {
     // Routing stuff here...
   }]);

controller.js:

controller.js:

angular.module('app.controllers', []).                                                                                                                                                                                  
  controller('firstCtrl', ['$scope', function($scope) {
    $scope.helpers = MyNamespace.helpers;
  });

然后在你的部分,你可以使用:

Then in your partial you can use:

<button data-ng-click="console.log(helpers.isNotString('this is a string'))">Log String Test</button>

旧的答案如下:

这可能是最好的,包括他们作为一个服务。如果你要重新使用它们跨越多个控制器,包括他们作为服务将让您不必重复code。

It might be best to include them as a service. If you're going to re-use them across multiple controllers, including them as a service will keep you from having to repeat code.

如果您想使用在HTML服务功能的部分,那么你应该将它们添加到该控制器的作用范围:

If you'd like to use the service functions in your html partial, then you should add them to that controller's scope:

$ scope.doSomething = ServiceName.functionName;

然后在你的部分,你可以使用:

Then in your partial you can use:

<button data-ng-click="doSomething()">Do Something</button>

下面是你可能会保持一种方式这一切组织和太多的麻烦免费的:

Here's a way you might keep this all organized and free from too much hassle:

分离控制器,服务和路由code /配置分为三个文件:controllers.js,services.js和app.js.顶层模块是应用程序,里面有app.controllers和app.services作为依赖。然后app.controllers和app.services可以声明为自己的文件模块。这种组织结构是刚刚从角种子采取:

Separate your controller, service and routing code/config into three files: controllers.js, services.js, and app.js. The top layer module is "app", which has app.controllers and app.services as dependencies. Then app.controllers and app.services can be declared as modules in their own files. This organizational structure is just taken from Angular Seed:

app.js:

 angular.module('app', ['app.controllers', 'app.services']).                             
   config(['$routeProvider', function($routeProvider) {
     // Routing stuff here...
   }]);  

services.js:

services.js:

 /* Generic Services */                                                                                                                                                                                                    
 angular.module('app.services', [])                                                                                                                                                                        
   .factory("genericServices", function() {                                                                                                                                                   
     return {                                                                                                                                                                                                              
       doSomething: function() {   
         //Do something here
       },
       doSomethingElse: function() {
         //Do something else here
       }
    });

controller.js:

controller.js:

angular.module('app.controllers', []).                                                                                                                                                                                  
  controller('firstCtrl', ['$scope', 'genericServices', function($scope, genericServices) {
    $scope.genericServices = genericServices;
  });

然后在你的部分,你可以使用:

Then in your partial you can use:

<button data-ng-click="genericServices.doSomething()">Do Something</button>
<button data-ng-click="genericServices.doSomethingElse()">Do Something Else</button>

这样,你只有code的一行添加到每个控制器都能够访问任何服务功能,无论是范围访问。

That way you only add one line of code to each controller and are able to access any of the services functions wherever that scope is accessible.

这篇关于如何添加一些小工具功能,以我的AngularJS应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆