Ram Guiao Ram Guiao - 1 year ago 64
Javascript Question

$scope not updating unless called twice

Please see my codes below. I am having a hard time showing the value of $scope.brand in my view. When I click the get user brand button nothing happens. The brand.name in the view didn't updated but when I click the test brand button after I clicked the get user brand button, the value of the scope will show. I don't know what's happening now. Please help. Thank you!


var app = angular.module('nwApp', [], function($interpolateProvider) {

var url = 'http://localhost:3000';

app.controller('brandsCtrl', ['$scope', '$http', function($scope, $http){

$scope.brands = {};
$scope.brand = {};

$scope.brands = result;

$scope.getAssignUser = function(brand_id){
$scope.brand = result;


$scope.checkBrand = function(){


<a href="javascript:void(0)" class="btn btn-warning" title="Assign User for this Brand" ng-click='getAssignUser(brand._id)' >GET USER BRAND</a>

<a href="javascript:void(0)" class="btn btn-warning" ng-click='checkBrand()' > TEST BRAND </a>

<div><% brand.name %></div>

Answer Source

The problem is here:

                $scope.brand = result;

$.get is jquery so when it updates the $scope.brand in the success the digest cycle will not run and reflect the value.

You should make use of the $http service provided by angular for doing ajax:

  method: 'GET',
  url: url+'/brands/'+brand_id
}).then(function successCallback(result) {
     $scope.brand = result;
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.

Other solution is:

In your jquery ajax you change the scope variable inside $apply like this:

                $scope.$apply(function (){$scope.brand = result;});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download