Jimmie
Jimmie

Reputation: 407

ng-repeat with JSON object not printing

I have a controller chatController.js and a 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 is specified in header elsewhere, the sendMessage() function works ok.

The problem is that when clicking getMessage in the GUI, the ng-repeat is not creating a list from the channel which is set with response.messages in the controller.

The response json looks like this:

{
    "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
}

Upvotes: 0

Views: 254

Answers (1)

Dmitriy
Dmitriy

Reputation: 3765

Make sure that your Chat.getMessageexecute inside $digest loop of angular. You can try this by this code:

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
    });

if $scope.$apply() will not trigger error then your code executing outside of angular $digest loop.

Upvotes: 1

Related Questions