1

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?

5
  • Why are you using ajax rather that $http service? Commented Jan 11, 2016 at 10:08
  • As I mentioned, just out of curiosity. :-) Commented Jan 11, 2016 at 10:10
  • I didnt read it carefully, my bad! :-) Commented Jan 11, 2016 at 10:11
  • $http is better integrated with the AngularJS digest cycle. The other benefit of $http is that it returns $q promises which are also better integrated with the digest cycle. Commented Jan 11, 2016 at 10:21
  • Yeah, I got a lot to learn. Commented Jan 11, 2016 at 10:30

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

6 Comments

I would wrap the scope variable assignment inside of scope.apply, as outlined in this article: jimhoskins.com/2012/12/17/angularjs-and-apply.html.
Thx a lot for your answer and suggestion. I'm pretty familiar with jquery but new to the angular, so cant stop thinking in jquery.
I think this link would be helpful: stackoverflow.com/questions/14994391/…
It sure will be! Thx, again.
And may I ask why the other two respondent delete their answers?
|
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.