简体   繁体   English

在AngularJS控制器中使用第三方过滤器

[英]Using a Third-Party Filter in AngularJS Controller

I am working on an AngularJS app. 我正在开发AngularJS应用。 I am using underscore.string in my views. 我在视图中使用underscore.string For example, I have code that looks like this in my views: 例如,我的代码在我的视图中看起来像这样:

<h3>Welcome { user.firstName | _.str: 'capitalize' }}</h3>

I need to use the capitalize function in the controller that's associated with this view. 我需要在与此视图关联的控制器中使用大写功能。 In an attempt to do that, I have the following: 为了做到这一点,我有以下几点:

.controller('MyCtrl', function ($scope, $location, $filter) {
    $scope.user = null;
    $scope.defaultValue = null;

    $scope.initialize = function() {
      $scope.user = getUser();
      $scope.defaultValue = $filter('capitalize')('my value');
    };
    $scope.initialize();
})

Everything works until I try to all the capitalize filter. 一切正常,直到我尝试全部使用大写过滤器。 What am I doing wrong? 我究竟做错了什么? I get an error that says: 我收到一条错误消息:

Unknown provider: capitalizeFilterProvider <- capitalizeFilter

I can't figure out what I'm doing wrong. 我不知道我在做什么错。 It seems odd that it works fine in my view but now my controller. 在我看来,但现在是我的控制器,它工作正常似乎很奇怪。

register your filter as a dependency in your app 在您的应用程序中将过滤器注册为依赖项

angular.module('app', ['ngRoute','capitalize']);

for more info look at the documentation 有关更多信息,请参阅文档

EDIT: create the angular filter and use it as a wrapper for the underscore.string library: 编辑:创建角度过滤器,并将其用作underscore.string库的包装器:

angular.module('app', []).filter('capitalize', function() {
  return function(input) {
    return _.str.capitalize(input)
  };
});

in your template: 在您的模板中:

<h3>Welcome { user.firstName | capitalize }}</h3>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM