如何使用angularJS分割字符串 [英] How to split a string with angularJS

查看:105
本文介绍了如何使用angularJS分割字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在 angularJS 中简单地拆分字符串.我有我的

I wanted to know if I can split a string simply in angularJS. I have my

 $scope.test = "test1,test2";

在我的控制器和我看来,我想做这样的事情

in my controller and in my view, I wanted to do something like that

{{test[0] | split(',')}}
{{test[1] | split(',')}}

我已经看到很多关于 input 和 ng-change 在控制器中调用一个函数来分割字符串或使用 ng-list 的东西,但在我的情况下没有任何作用.

I've seen a lot thing about input and ng-change calling a function in the controller that split the string or something with ng-list but nothing works in my case.

谢谢大家.

推荐答案

您可能希望将该功能包装到过滤器中,这样您就不必将 mySplit 函数放在所有控制器中.例如

You may want to wrap that functionality up into a filter, this way you don't have to put the mySplit function in all of your controllers. For example

angular.module('myModule', [])
    .filter('split', function() {
        return function(input, splitChar, splitIndex) {
            // do some bounds checking here to ensure it has that index
            return input.split(splitChar)[splitIndex];
        }
    });

从这里,您可以按照您最初的意图使用过滤器

From here, you can use a filter as you originally intended

{{test | split:',':0}}
{{test | split:',':0}}

更多信息请访问 http://docs.angularjs.org/guide/filter(感谢 ross)

More info at http://docs.angularjs.org/guide/filter (thanks ross)

Plunkr @ http://plnkr.co/edit/NA4UeL

这篇关于如何使用angularJS分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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