【问题标题】:ng-repeat with JSON object not printingng-repeat 不打印 JSON 对象
【发布时间】:2016-03-10 15:28:45
【问题描述】:

我有一个控制器 chatController.js 和一个 chat.html

chatController.js

$scope.getMessage = function() {
    Chat.getMessage("C0RRZEDK4")
    .success(function(response) {
        console.log("getMessage: " + JSON.stringify(response));

        $scope.channel = response.messages;
    });
}

chat.html

<div ng-controller="ChatController">
    <form>
        <input ng-style="style(color)" type="text" ng-model="text" placeholder="text">
        <button ng-click="sendMessage()">Send!</button>
        <button ng-click="getMessage()">Get First Message!</button>

    </form>

    <li ng-repeat="msg in channel">
        <li>{{msg.text}}</li>

    </li>

*ng-app 在其他地方的标头中指定,sendMessage() 函数可以正常工作。

问题在于,当在 GUI 中单击 getMessage 时,ng-repeat 不会从控制器中使用 response.messages 设置的 channel 创建列表。

响应 json 如下所示:

{
    "ok":true,"messages": [
        {
        "type":"message",
        "user":"U0KTA20K0",
        "text":"123",
        "ts":"1457615693.000003"
        },

        {
         "user":"U0KTA20K0",
         "type":"message",
         "subtype":"channel_join",
         "text":"<@U0KTA20K0|julian_blair> has joined the 
channel","ts":"1457615234.000002"}
    ],

"has_more":false
}

【问题讨论】:

  • 它是我编写的一个有角度的对象,传递到 $scope 服务旁边的控制器中。
  • $scope.channel = (JSON.stringify(response)).messages
  • &lt;div&gt;{{channel}}&lt;/div&gt; 添加后会在您的页面上呈现什么?
  • 打印:[{"type":"message","user":"U0KTA20K0","text":"123","ts":"1457615693.000003"},{"user":"U0KTA20K0","type":"message","subtype":"channel_join","text":"&lt;@U0KTA20K0|julian_blair&gt; has joined the channel","ts":"1457615234.000002"}]

标签: javascript html angularjs json angularjs-ng-repeat


【解决方案1】:

确保您的 Chat.getMessageexecute 在 $digest 角度循环内。您可以通过以下代码尝试:

Chat.getMessage("C0RRZEDK4")
    .success(function(response) {
        console.log("getMessage: " + JSON.stringify(response));

        $scope.channel = response.messages;
        $scope.$apply() // if it is inside $digest loop it will trigger an error
    });

如果$scope.$apply() 不会触发错误,那么您的代码在角度$digest 循环之外执行。

【讨论】:

  • 我添加了 $scope.$apply() 并在浏览器控制台中触发了错误:Error: [$rootScope:inprog]
  • 看起来一切正常 )) 尝试将 $scope.channel = []; 定义为初始值。
  • 解决了问题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多