javascript Angularjs 中的子字符串使用过滤器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20394181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:24:03  来源:igfitidea点击:

Substring in Angularjs using filters?

javascriptangularjs

提问by karthick

I am having the following array that i want to manipulate in DOM using Angularjs with some filters

我有以下数组,我想使用带有一些过滤器的 Angularjs 在 DOM 中操作

$scope.urls = [{
    path: 'http://a.com/index'        
    }, {
     path: 'http://a.com/home'        
    }, {
    path: 'http://a.com/etc'        
    }, {
    path: 'http://a.com/all'        
   }];

I had tried to substring the path using filters but it is not working.

我曾尝试使用过滤器对路径进行子字符串化,但它不起作用。

Fiddle Demo

小提琴演示

Any help is great.

任何帮助都很棒。

回答by Maxim Shoustin

Try this one:

试试这个:

HTML

HTML

<div ng-controller = "fessCntrl"> 
  <h1>Only path without domain name:</h1>
        <ul>
            <li ng-repeat="url in urls | myCustomFilter">{{url.path}}</li>
        </ul>
</div>

JS

JS

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

fessmodule.controller('fessCntrl', function ($scope) {
     $scope.urls = [{
        path: 'http://a.com/index'        
    }, {
         path: 'http://a.com/home'        
    }, {
        path: 'http://a.com/etc'        
    }, {
        path: 'http://a.com/all'        
    }];

    $scope.otherCondition = true;
});
fessmodule.$inject = ['$scope'];

 fessmodule.filter('myCustomFilter', function() {
   return function( urls) {
    var filtered = [];

    angular.forEach(urls, function(url) {
        filtered.push( {path:url.path.substring("http://a.com".length, url.path.length)});
    });

    return filtered;
  };
});

Demo Fiddle

演示 Fiddle

As a side note:

作为旁注:

Try to write filters out of controller.

尝试将过滤器写出控制器。

回答by David Renner

AngularJS v 1.4.5 supports a standard "limitTo" filter for arrays(including string) with parameters length and offset:

AngularJS v 1.4.5 支持带有参数长度和偏移量的数组(包括字符串)的标准“limitTo”过滤器:

<div ng-controller = "SampleController"> 
  <h1>Result of substring equivalent filter:</h1>
        <ul>
            <li ng-repeat="url in urls">{{url.path | limitTo:5:12}}</li>
        </ul>
</div>

Note: This solution fails in case of dynamic domain length("http://a.com" static length of 12).

注意:此解决方案在动态域长度(“ http://a.com”静态长度为 12)的情况下失败。

Note 2: Increase length to the maximum resulting length of path(Max is "index" having length of 5).

注 2:将长度增加到路径的最大结果长度(最大是长度为 5 的“索引”)。

Overview of all filterssupported by AngularJS out of the box.

开箱即用的 AngularJS 支持的所有过滤器的概述