AngularJS:NG-重复中修改值 [英] AngularJS: modify value within ng-repeat

查看:88
本文介绍了AngularJS:NG-重复中修改值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的表角:

<table>
    <tr ng-repeat="row in $data">
        <td>{{row.name}}</td>
        <td>{{row.surname}}</td>
    </tr>
</table>

这会使这样的:

<table>
    <tr>
        <td>Johnathan</td>
        <td>Smith</td>
    </tr>
    <tr>
        <td>Jane</td>
        <td>Doe</td>
    </tr>
</table>

但我必须重新加载表动态搜索功能,我需要突出像这样结果的搜索字符串(搜索词是约翰):

but I have a dynamic search function that reloads the table and I need to highlight the search string in results like so (the search word is "John"):

<table>
    <tr>
        <td><span class="red">John</span>athan</td>
        <td>Smith</td>
    </tr>
</table>

现在我希望像这样的工作:

now I hoped that something like this would work:

<table>
    <tr ng-repeat="row in $data">
        <td>{{myFunction(row.name)}}</td>
        <td>{{row.surname}}</td>
    </tr>
</table>

但事实并非如此。什么办法,使这项工作?

but it doesn't. Any way to make this work?

更新:解决,建议在这种情况下@loan工程解决方案

UPDATE: Solved, solution proposed by @loan works in this case.

推荐答案

正如您将在下面的例子中看到的,你可以做一些类似的。

As you'll see in the example below, you can do something similar to this.

在现有的循环中,您可以添加自定义过滤器如下:

In your existing loop you can add the custom filter as follows:

<body ng-controller="TestController">
  <h1>Hello Plunker!</h1>
  <input type="text" ng-model="query" />

  <ul>
    <li ng-repeat="item in data | filter:query">
      <!-- use the custom filter to highlight your queried data -->
      <span ng-bind-html="item.name | highlight:query"></span>
    </li>
  </ul>
</body>

在你的JavaScript文件,您可以创建自定义过滤器:

In your JavaScript file you can create the custom filter:

(function() {
  'use strict';

  angular.module("app", []);

  //to produce trusted html you should inject the $sce service
  angular.module("app").filter('highlight', ['$sce', function($sce) {

    function escapeRegexp(queryToEscape) {
      return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
    }

    return function(matchItem, query) {
      return $sce.trustAsHtml(query ? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '<strong>$&</strong>') : matchItem);
    };
  }]);

  angular.module("app")
    .controller('TestController', ['$scope',
      function($scope) {

        $scope.query = ""; //your scope variable that holds the query

        //the dummy data source
        $scope.data = [{
          name: "foo"
        },{
          name: "bar"
        },
        {
          name: "foo bar"
        }];
      }
    ]);

})();

如果你愿意,你可以用你的价值观更换过滤器的HTML:

if you want you can replace the html in the filter with your values:

<strong>$&</strong>

<span class="red">$&</span>

这篇关于AngularJS:NG-重复中修改值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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