【问题标题】:Edit JSON Response in AngularJS and bind to the list在 AngularJS 中编辑 JSON 响应并绑定到列表
【发布时间】:2014-04-14 04:33:25
【问题描述】:

您好,我知道如何读取 json 表单并将输出绑定到视图,但是我想在输出和投标转换后的数据中添加一些逻辑。如何将我的 forEach 输出到数组,而不是基于它进行 ng-repeat 或将我的 ajax 数据绑定与我的修改结合起来?

此刻如果我改变

$scope.fleet = newData; => $scope.fleet = 数据;

和 view.html 例如。 {{item.name}} 一切正常,但我想在绑定之前对名称进行一些更改。

我的代码:

controler.js

function LoadFleetControler($scope){
$.ajax({
  url: 'https://someapi/list',
  type: 'GET',
  dataType: 'json',
  success: function (data) {

  var newData = [];

  angular.forEach(data, function(value, key){

  /* ############################ Options ############################ */

  var d = new Date();
  var month = d.getMonth() + 1;
  var thisDate = d.getDate() + '/' + padLeft(month,2)  + '/' + d.getFullYear();
  var thisCycle = dateToDays(thisDate, value.end_bill_date) + 1; // Include last 24H


   /* ############################ Scope ############################ */


   $scope.fleetUser = value.name;
   $scope.fleetCycle = 'Cycle: ' + thisCycle + ' days left (' + value.end_bill_date + ')';
   $scope.fleetPercentageUsed = value.percentage_used;
   $scope.fleetCycleColor = highlighSwitch(value.percentage_used);

}, newData);

console.log(newData);

$scope.fleet = newData;
$scope.$apply();

},
error: function(data) {

$scope.error = true;
$scope.$apply();

}
});  

}

view.html

<div ng-controller="LoadFleetControler">
<ons-list>
<ons-list-item ng-show="error">Server Connection Error</ons-list-item>
<ons-list-item class="topcoat-list__item__line-height" ng-repeat="item in fleet">
{{fleetUser}}
<small>{{fleetCycle}}</small>
</ons-list-item>
</ons-list>
</div>

【问题讨论】:

    标签: json angularjs angularjs-ng-repeat


    【解决方案1】:

    angular.forEach() 中,您正在将项目分配给范围,而您可能打算创建新对象并将它们添加到newData 数组中...

    angular.forEach(data, function(value, key){
    
            // ...
    
            var newItem = {};
            newItem.fleetUser = value.name;
            newItem.fleetCycle = 'Cycle: ' + thisCycle + ' days left (' + value.end_bill_date + ')';
            newItem.fleetPercentageUsed = value.percentage_used;
            newItem.fleetCycleColor = highlighSwitch(value.percentage_used);
    
            newData.push(newItem);
        }
    );
    

    【讨论】:

    • 您好,我得到的示例是:未捕获的 TypeError: Object [object global] has no method 'push'
    • angular.forEach之前还有var newData = [];吗?
    • 是的,问题出在 this.push(newItem) 与 newData.push(newItem);谢谢
    • 再想一想如何将 HTML 添加到 angular 变量中?例如。 newItem.fleetCycleColor = '

      ' + value.percentage_used + '

      '; $scope 总是将 HTML 输出为文本而不是 HTML?
    • 奇怪...如果newData 存在并且它作为上下文传递到angular.forEach()this 应该是newData...无论如何,我会更新答案。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    • 1970-01-01
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-29
    相关资源
    最近更新 更多