search

Home  >  Q&A  >  body text

angular.js - $.post in angular cannot be bound to $scope (difference in usage between $.post and $http.post)

As shown below, if the $scope.equipments=... section is placed in $.post, it cannot be bound to $scope.equipments. If it is placed outside, it can be bound. Why is this?


mainApp.controller('equipmentsController', function($scope, $http) { $.post("getAllDeviceList.action", {}, function(response){ $scope.equipments = [ { "id" : "1", "name" : "equipment01 ", "number" : "11" }, { "id" : "2", "name" : "equipment02 ", "number" : "22" }, { "id" : "3", "name" : "equipment03 ", "number" : "33" } ]; } ); $scope.equipments = [ { "id" : "1", "name" : "equipment01 ", "number" : "11" }, { "id" : "2", "name" : "equipment02 ", "number" : "22" }, { "id" : "3", "name" : "equipment03 ", "number" : "33" } ]; }
大家讲道理大家讲道理2861 days ago577

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-05-15 16:54:49

    After being reminded by @lee1994522, I realized that if the $.post method is used, then 脱离了angular的上下文 it cannot be bound to Angular’s ​​$scope.

    this is the point,pls.. $.post is not an Angular issue and the stuff
    it wraps is not in an Angular world,so it's obviously that the
    equipments outside is in Angular's world and it works as you expect

    try $scope.$apply() when you call a "none Angular" issue if you wanna
    refresh sth

    There are two solutions:

    $.post

    The first one is as @lee1994522 said, directly add a sentence $scope.$apply() at the end of the $.post callback function to synchronously bind the changes to the view

    $.post("xxx.action",
                {},
                function(response){
                    if(response.result == "success"){
                        ...
                        }
                        $scope.equipments = equipments; 
                        $scope.$apply();
                    }
                },
                "json"
        );
    

    $http.post

    AngularJS - Any way for $http.post to send request parameters instead of JSON

    Global definition:


    var app = angular.module('myApp'); app.config(function ($httpProvider) { $httpProvider.defaults.transformRequest = function(data){ if (data === undefined) { return data; } return $.param(data); } $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'; });

    Then write in the controller:

       $http.post("xxx.action").success(function(response) {  
                ...
                $scope.equipments = equipments; 
        });
    

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-15 16:54:49

    I don’t understand the original poster’s use of $.post. What’s the point of injecting $http

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-15 16:54:49

    Your$.post不是angular的方法,所以实际上post的回调虽然执行了,但angular在视图上却不知道这件事。你可以在$.post里的赋值操作后面再跟一句$scope.$apply();, that assignment operation will take effect.

    reply
    0
  • Cancelreply