Halt
Halt

Reputation: 1135

Why angular data-binding not working with jquery ajax?

I'm working on the angular tutorial project ---- angular-phonecat, and I got to the step-5.

Out of curiosity, I replace the original angular ajax method with jquery ajax method and left the rest untouched. After that I found I can get the right data from server but the data-binding never works.

Here is my code :

'use strict';

/* Controllers */

var phonecatApp = angular.module('phonecatApp', []);

phonecatApp.controller('PhoneListCtrl', ['$scope', '$http', function ($scope, $http) {
    //$http.get('phones/phones.json').success(function(data) {
    //  $scope.phones = data;
    //});
    $.ajax({
        type: "GET",
        url: "phones/phones.json",
        contentType: "application/json",
        global: false,
        success: function (data) {
            $scope.phones = data;
        }
    });

    $scope.orderProp = 'age';
}]);

Why would this happen? Am I miss anything important?

Upvotes: 1

Views: 957

Answers (2)

Tarun Dugar
Tarun Dugar

Reputation: 8971

This is happening because jQuery's ajax function is not within the angular digest cycle. To fix this use $scope.$apply(); to run the cycle explicitly:

$scope.phones = data;
$scope.$apply();

Also, one piece of advice: try to use as less jQuery(use it for DOM manipulations mainly) as possible otherwise you won't be able to learn the 'angular' way.

Upvotes: 5

Chanthu
Chanthu

Reputation: 1794

You would have to do $scope.$apply() to let angular know to run watch/digest cycle if code is run outside of angular.

$http is monitored by angular where as ajax is not.

Upvotes: 0

Related Questions