使用angularJS遇見的一些問題的解決方案

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   使用   ar   strong   

1. angularJS的$http.post請求,SpringMVC後台接收不到參數值的解決方案

問題一般為:400 Required String parameter ‘rPassword‘ is not present 或其他400錯誤

解決方案 一:修改源碼http://my.oschina.net/buwei/blog/191640   (可以詳細瞭解請求接收不到的原因)

解決方案 二:感覺修改源碼總是不好滴,可以採用這個方法,修改提交參數config的headers和transformRequest

(1) 建立一個全域的transformRequest function

var app = angular.module(‘myApp‘);app.config(function ($httpProvider) {    $httpProvider.defaults.transformRequest = function(data){        if (data === undefined) {            return data;        }        return $.param(data);    }});

 

然後為每一個方法或者建立一個全域的Content-Type header

$httpProvider.defaults.headers.post[‘Content-Type‘] = ‘application/x-www-form-urlencoded; charset=UTF-8‘;

 

(2) 為每一個需要的方法建立局部的transformRequest

var transform = function(data){        return $.param(data);    }    $http.post("/foo/bar", requestData, {        headers: { ‘Content-Type‘: ‘application/x-www-form-urlencoded; charset=UTF-8‘},        transformRequest: transform    }).success(function(responseData) {        //do stuff with response    });

 

參考網址AngularJS - Any way for $http.post to send request parameters instead of JSON?

2. scope.$apply的使用

問題一般為:資料雙向繫結失效,就是明明在controller裡面給$scope.×××賦值了,在頁面上xxx愣是顯示不了,但是點擊一下輸入框或是form表單的提交按鈕,xxx資料資訊就顯示了,是不是好坑啊。

解決方案 : 添加 $scope.$apply()

例如

$scope.$apply(function(){   $scope.xxx = “你賦的值”;
});

原因

一般情況下是不需要我們手動添加這一句代碼的,因為angularJS本身在需要的時候調用,以達到我們所看到的資料雙向繫結的效果。

但是你若是引用一個外部外掛程式或者其他,在回呼函數裡建立或更新$scope.xxx的資料,因為外部外掛程式本身已經脫離了angularJS的範圍,所以資料雙向繫結在這裡沒有效果,只能手動添加$scope.$apply()來通知頁面擷取資料。

3. 因為是新手,一步一步的來

使用angularJS遇見的一些問題的解決方案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.