如何在AngularJS应用程序中添加一些小实用程序功能?

Ala*_*an2 146 angularjs

我想在AngularJS应用程序中添加一些实用程序功能.例如:

$scope.isNotString = function (str) {
    return (typeof str !== "string");
}
Run Code Online (Sandbox Code Playgroud)

最好的方法是将它们添加为服务吗?从我所看到的,我可以做到这一点,但后来我想在我的HTML页面中使用这些,所以如果它们在服务中仍然可能吗?例如,我可以使用以下内容:

 <button data-ng-click="doSomething()"
         data-ng-disabled="isNotString(abc)">Do Something
 </button>
Run Code Online (Sandbox Code Playgroud)

有人能给我一个如何添加这些的例子.我应该创建服务还是有其他方法来实现它.最重要的是,我希望这些实用程序功能在一个文件中,而不是与主要设置的另一部分相结合.

我知道有一些解决方案,但没有一个是如此清晰.

解决方案1 - Urban提出的建议

$scope.doSomething = ServiceName.functionName;
Run Code Online (Sandbox Code Playgroud)

这里的问题是我有20个功能和10个控制器.如果我这样做,那将意味着为每个控制器添加大量代码.

解决方案2 - 由我提出

    var factory = {

        Setup: function ($scope) {

            $scope.isNotString = function (str) {
                return (typeof str !== "string");
            }
Run Code Online (Sandbox Code Playgroud)

这样做的缺点是,在每个控制器的开头,我会对通过$ scope的每个服务进行一次或多次这些Setup调用.

解决方案3 - Urban提出的建议

城市提出的创建通用服务的解决方案看起来很好.这是我的主要设置:

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);
Run Code Online (Sandbox Code Playgroud)

我应该将通用服务添加到此,我该怎么做?

urb*_*ons 106

编辑7/1/15:

我很久以前写过这个答案,并且一段时间以来没有用角度保持很多,但似乎这个答案仍然比较受欢迎,所以我想指出几点@nicolas以下是好的.首先,注入$ rootScope并在其中附加帮助程序将使您不必为每个控制器添加它们.另外 - 我同意如果您要添加的内容应该被视为Angular服务或过滤器,那么它们应该以这种方式被采用到代码中.

此外,从当前版本1.4.2开始,Angular公开了一个"Provider"API,允许将其注入配置块.请参阅以下资源:

https://docs.angularjs.org/guide/module#module-loading-dependencies

AngularJS依赖注入module.config中的值

我不认为我会更新下面的实际代码块,因为这些天我并没有真正积极地使用Angular而且我真的不想冒新的答案而不觉得它实际上符合新的最佳实践.如果其他人感觉到这一点,那么一定要去做吧.

编辑2/3/14:

在考虑了这个并阅读了其他一些答案后,我实际上认为我更喜欢@Brent Washburne和@Amogh Talpallikar提出的方法的变体.特别是如果你正在寻找像isNotString()或类似的实用程序.这里一个明显的优点是你可以在角度代码之外重复使用它们,你可以在配置函数中使用它们(你不能用服务做).

话虽这么说,如果你正在寻找一种通用的方法来重新使用应该适当的服务,我认为旧的答案仍然是一个很好的答案.

我现在要做的是:

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...
   }]);
Run Code Online (Sandbox Code Playgroud)

controller.js:

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

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

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

老答案如下:

最好将它们作为服务包含在内.如果您要在多个控制器中重复使用它们,将它们作为服务包括在内将使您不必重复代码.

如果您想在html partial中使用服务函数,那么您应该将它们添加到该控制器的范围:

$scope.doSomething = ServiceName.functionName;

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

<button data-ng-click="doSomething()">Do Something</button>
Run Code Online (Sandbox Code Playgroud)

这是一种你可以保持这种有条理并且没有太多麻烦的方式:

将控制器,服务和路由代码/配置分成三个文件:controllers.js,services.js和app.js. 顶层模块是"app",它有app.controllers和app.services作为依赖项.然后app.controllers和app.services可以在他们自己的文件中声明为模块.这个组织结构刚从Angular Seed中获取:

app.js:

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

services.js:

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

controller.js:

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

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

<button data-ng-click="genericServices.doSomething()">Do Something</button>
<button data-ng-click="genericServices.doSomethingElse()">Do Something Else</button>
Run Code Online (Sandbox Code Playgroud)

这样,您只需向每个控制器添加一行代码,并且只要该范围可访问,就可以访问任何服务功能.

  • @EricKeyte命名空间是一个对象文字,这是一种在JS中非常常见的单例.对不起延迟回复:) (3认同)

nic*_*las 31

来到这个旧线程,我想强调一下

1°)实用程序函数可以(应该?)通过module.run添加到rootscope.没有必要为此目的实例化特定的根级控制器.

angular.module('myApp').run(function($rootScope){
  $rootScope.isNotString = function(str) {
   return (typeof str !== "string");
  }
});
Run Code Online (Sandbox Code Playgroud)

2°)如果将代码组织到单独的模块中,则应使用角度服务工厂,然后将它们注入传递给运行块的函数中,如下所示:

angular.module('myApp').factory('myHelperMethods', function(){
  return {
    isNotString: function(str) {
      return (typeof str !== 'string');
    }
  }
});

angular.module('myApp').run(function($rootScope, myHelperMethods){ 
  $rootScope.helpers = myHelperMethods;
});
Run Code Online (Sandbox Code Playgroud)

3°)我的理解是,在视图中,对于大多数情况,您需要这些辅助函数将某种格式应用于您显示的字符串.在最后一种情况下你需要的是使用角度滤波器

如果你已经将一些低级辅助方法构建到角度服务或工厂中,只需将它们注入到过滤器构造函数中:

angular.module('myApp').filter('myFilter', function(myHelperMethods){ 
  return function(aString){
    if (myHelperMethods.isNotString(aString)){
      return 
    }
    else{
      // something else 
    }
  }
);
Run Code Online (Sandbox Code Playgroud)

在你看来:

{{ aString | myFilter }}   
Run Code Online (Sandbox Code Playgroud)


Wil*_*urn 6

我是否正确理解您只想定义一些实用程序方法并在模板中使用它们?

您不必将它们添加到每个控制器.只需为所有实用程序方法定义一个控制器,并将该控制器附加到<html>或<body>(使用ngController指令).您在<html>(意思是任何地方,期间)或<body>(除<head>之外的任何地方)附近的任何其他控制器将继承该范围,并且可以访问这些方法.