angular.js - angular里$.post无法绑定到$scope里($.post、$http.post用法区别)
大家讲道理
大家讲道理 2017-05-15 16:52:49
[AngularJS讨论组]

如下所示,如果$scope.equipments=...那一段,放在$.post里就不能绑定到$scope.equipments上,如果放在外面就可以,这是为什么?


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" } ]; }
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(3)
PHP中文网

经过@lee1994522 的提醒,意识到如果用了$.post方法,那么脱离了angular的上下文,所以无法绑定到angular的$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

解决办法有两个:

$.post

第一个诚如@lee1994522所说,直接在$.post的回调函数的最后加上一句$scope.$apply(),把改变同步绑定到视图上

$.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

全局里定义:


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'; });

然后控制器里面写:

   $http.post("xxx.action").success(function(response) {  
            ...
            $scope.equipments = equipments; 
    });
曾经蜡笔没有小新

搞不懂楼主用$.post的意义。你注入$http又有何意义

给我你的怀抱

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号