Moslem7026
Moslem7026

Reputation: 3338

Angular two way DataBinding , Update model from Ajax Call

 <input ng-model="titlelangnative" id="titlelangnative" name="titlelangnative" type="text" />

Getting Value of model from view (html) to controller (js) file Works fine via var x = $scope.titlelangnative but when i call ajax url and get data and then assign value to titlelangnative model by $scope.titlelangnative = json.data it doesnt update view immediately, and when i click on one of dom object that are binded then value being Updated.

angularFormsApp.controller('efController',
    ["$scope", "$window", "$routeParams",
        function efController($scope, $window, $routeParams) {
            var siteRoot = dnn.getVar("sf_siteRoot", "/");
            $.ajax({
                type: 'GET',
                url: siteRoot + "DesktopModules/MVC/Ycon/Item/GetDraft",
                beforeSend: sf.setModuleHeaders,
                success: function (data, status, xhr) {
                    var result = JSON.parse(data);
                        //this part not update text box in html until i click on it
                        $scope.titlelangnative = result.title_langNative;
                    },
                    error: function (data, status, xhr) {
                        $("#gotobankloader").addClass('hidden');
                        alert('error');
                    }
                });

why text box model value not update after ajax response?

Upvotes: 0

Views: 28

Answers (1)

Devansh J
Devansh J

Reputation: 4194

Umm... First of all don't use jQuery's $.ajax... Instead use angularjs's $http... That will solve the problem...

The reason why $.ajax doesn't work is becuase let's say the request takes 1 sec and thus the model changes after 1 sec and angularjs does not changes the view because you didn't tell to update it... (Thus the view changes when you click it because by clicking it you are telling angularjs to update the view by firing an dom event)

To fix this you'll have to call $scope.$apply() to update the view after the request is complete... Something like this

$.ajax({
  ....
  success: function(){
    ...
    $scope.$apply();
  }
})

But when you are using $http angular fires $scope.$apply() on it's own...

So it's recommended to use $http

Upvotes: 1

Related Questions