0

I'm just learning Angular JS. I'm trying to populate the scope variable with the result of an ajax database call. The ajax call returns a propper json object(an array) but I cannot get $scope.contentType to output on my HTML page.

Can anyone see any reason this should not work?

app.controller('MainController', ['$scope', function($scope){
    var allMyData;
    $scope.title = 'Content Types List';

    var request = $.ajax({
        type: "POST",
        dataType: "json",
        url: "/angularJS/dbServices.cfc?method=getContentTypes"
    })

    request.done(function(data){
        allMyData = data.DATA;
        console.log(allMyData);
        $scope.contentTypes = allMyData;
    })

    request.fail(function(){
        console.log('fail');
    })
}])
0

2 Answers 2

6

The reason your $scope isn't updating on the view is because you are changing that value outside the $digest cycle. You need to use AngularJS' built-in $http service.

You can get more information/documentation in the link above.

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

Comments

1

It is because you are using jQuery ajax which is not triggering angular digest. You can fix it with:

 request.done(function(data){
    $scope.apply(function() {
      allMyData = data.DATA;
      console.log(allMyData);
      $scope.contentTypes = allMyData;
    })
})

However, this is not the best practice. Instead you should 1) use $http service as mentioned in other answer 2) Move the entire logic to a separate service 3) use a high-level interface provided by ngResource

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.