简体   繁体   English

AngularJS JSON处理(例如ng-repeat)

[英]AngularJS JSON Processing (like with ng-repeat)

I'm trying to process json data in following manner: 我正在尝试以以下方式处理json数据:

$scope.activities = response.data;
console.log($scope.activities.length);
var list = [];
for (var i = 0; i < $scope.activities.length; i++) {
    console.log($scope.activities[i].name);
    list.push($scope.activities[i].name);
}
var input = document.getElementById("myinput");
new Awesomplete(input, {
    list: list
}); 

Or how it's possible too (another case, but same principle): 或者也有可能(另一种情况,但原理相同):

<li ng-repeat="navItem in navItems" ng-click="itemClicked(item, $index)" ng-class="{'nav_list_item-current' : navItem.selected} " class="nav_list_item pure-u-md-1-{{navItemsCount}} pure-u-1-1">
    <a class="nav_list_item_link" href="{{navItem.link}}">
        {{navItem.name}}
    </a>
</li>

Where navItems is a JSON object. 其中navItems是一个JSON对象。

How is this possible in angular, I mean it's working but not really nice ? 我想这可能如何在角度上起作用,但不是很好吗?

Note that you could put your awesomecomplete code in a directive to have "clean angular", but that's not really a five minute thing. 请注意,您可以将令人敬畏的完整代码放在指令中以具有“干净的角度”,但这实际上并不是五分钟的事情。 Here is your database call data assignment simplified: 这是简化的数据库调用数据分配:

YourDatabaseCall().then(function(activitiesDataFromDb){
    //the _.pluck method gets you an array of activity names
    $scope.activities = _.pluck(activitiesDataFromDb, 'name');

    var input = document.getElementById("myinput");
    new Awesomplete(input, {
        list: list
    }); 
});

See http://underscorejs.org/#pluck , to copy their description of the pluck helper: 请参阅http://underscorejs.org/#pluck ,以复制其对pluck助手的描述:

A convenient version of what is perhaps the most common use-case for map: extracting a list of property values. 地图的最常见用例的便捷版本:提取属性值列表。 And their eexample: 和他们的eexample:

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.pluck(stooges, 'name');
=> ["moe", "larry", "curly"] 

Use Array.prototype.map 使用Array.prototype.map

var input = document.getElementById("myinput");

$scope.activities = response.data;

var activityNames = $scope.activities.map(function(item){
    return item.name;
});

new Awesomplete(input, {
    list: activityNames
});

or even shorter 甚至更短

var input = document.getElementById("myinput");

new Awesomplete(input, {
    list: response.data.map(function(item){
        return item.name;
    })
});

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

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