【问题标题】:How can I change a value inside of ng-repeat after the repeat complete?重复完成后如何更改 ng-repeat 内部的值?
【发布时间】:2016-10-06 12:55:09
【问题描述】:

我有一个 JSON,它为我提供了用户的工作经验信息。但国家和城市以代码格式提供(TR、DE 等) 我正在使用 ng-repeat 像这样将它们传递到 html 中

<div ng-repeat="e in experiences">
   <span>{{e.Name}}</span>
   <span ng-init="changeCodeToFullName(e.Country)">{{vm.CountryFullName[$index]}}</span>
</div>

我正在使用 ng-init 将国家代码转换为全名。 changeCodeToFullName 是我编写的角度服务,这是正确的方法吗?如果是,我无法访问 dom 来更改 CountryFullName 值。我试图在vm.CountryFullName[0]="TEST" 之类的JS 文件中访问它们,但没有成功。之后我需要使用 e.Country 变量,因此我无法更改原始的 .e.Country 值。

在 ng-repeat 完成后如何访问 ng-repeat 中的变量?

【问题讨论】:

    标签: angularjs angularjs-ng-repeat


    【解决方案1】:

    如何使用自定义filter

    <div ng-repeat="e in experiences">
        <span>{{e.Name}}</span>
        <span>{{e.Country | changeCodeToFullName}}</span>
    </div>
    
    angular.module('App').filter('changeCodeToFullName', function(YourService) {
        return function(country) {
            return YourService.getFullCountryName(country)
        }
    })
    

    这是一个例子:http://codepen.io/rustydev/pen/YWyqJB

    【讨论】:

    • 我尝试过过滤,但我在 html 中看到了 {}。我的过滤代码是这样的:app.filter('changeCountryCodeToFullName', function(testService) { return function(countryCode) { return testService.getCountryName(countryCode) .then(function (result) { console.log(222,result); return result; }) } }) 我可以在控制台看到结果。
    • 我的服务正在使用 $q 承诺。因为我正在使用 Web API 获取这些数据。我想这就是问题所在。
    • 我看过这个egghead.io/lessons/…,我解决了这个问题,谢谢
    【解决方案2】:

    这是一种方法 - 但如果列表更新,则不会重新解析此 ngInit 值。为什么不直接格式化 JSON 请求响应中的数据——比如:

    $http.get("json.json").success(function(data) {
        $scope.exeriences = data.map(function(obj) {
            //Format results;
            if (obj.Country == "DE") {
                obj.Country = "Germany"; //etc
            }
            return obj;
        });
    });
    

    【讨论】:

    • 我不能,因为列表太长了。我必须动态地做。我有另一项服务可以将代码更改为全名。我想使用这个服务,列表不会动态更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 1970-01-01
    • 2016-09-08
    • 2014-09-29
    • 2014-08-18
    • 2014-12-28
    相关资源
    最近更新 更多