AngularJS開發中常用的寫法,如:獲取URL參數、路由跳轉、$http、獲取元素等


控制器,帶狀態

app.controller('editCtrl', ['$http', '$location', '$rootScope', '$scope', '$state', '$stateParams', function($http, $location, $rootScope, $scope, $state, $stateParams){
    // 上邊聲明添加顯示的依賴注入,是為了防止,壓縮(如UglifyJS)時改變function里的參數名,造成功能引用失敗。推薦r.js壓縮
    // do something...
}

獲取路由的參數

$stateParams.id // #/camnpr/editCtrl?id=1

跳轉路由狀態

$state.go('camnpr.appManager'); // 跳轉后的URL: #/camnpr/appManager 
$location.path('camnpr/appManager'); // 功能也是跳轉的

ui-router擴展的跳轉方式

<a ui-sref="camnpr.appManager">跳轉</a> // 需要angular-ui-router

ng-repeat里顯示序號: $index // 這個是從0計數的。

 

get請求

$http({
&nbsp; &nbsp; method: 'get',
&nbsp; &nbsp; url: 'http://camnpr.com/getAPI/',
&nbsp; &nbsp; params:{id: 1}, 
&nbsp; &nbsp; headers: {'x-camnpr-uid': '1000'}//可以加入任意的頭信息
 });

 

 

post請求

$http({
&nbsp; &nbsp; method: 'post',
&nbsp; &nbsp; url: 'http://camnpr.com/postAPI/',
&nbsp; &nbsp; data:'id=1&referrer=camnpr.com', // 這里是字符串,格式請注意,同時我們可以使用 $.param({id:1, referrer: 'camnpr.com'})來獲取等價的形式。
&nbsp; &nbsp; // Form Data獲取方式 Request.Form['id'] 。 
&nbsp; &nbsp; //這是加'Content-Type': 'application/x-www-form-urlencoded',的功勞。
&nbsp; &nbsp; // 若不加'Content-Type',則:Request Payload:id=1&referrer=camnpr.com
&nbsp; &nbsp; // data: {id: 1, referrer: 'camnpr.com'}, // 是對象,那么 Form Data的數據是:{"id":1,"referrer":"camnpr.com"}:
&nbsp; &nbsp; headers: {'Content-Type': 'application/x-www-form-urlencoded', 'x-camnpr-uid': '1000'}
 });

  

根據selector獲取元素

angular.element('.is_select') // [<input type="checkbox" value="1" class="is_select">]

循環獲取並操作

angular.forEach(document.getElementsByClassName('is_select'), function(item, index){
&nbsp; &nbsp; if(item.checked){
&nbsp; &nbsp; &nbsp; &nbsp; ids+=item.value+',';
&nbsp; &nbsp; }
});

ng-click里帶當前的a,button等的事件

<button ng-click="camnpr.submitAdd($event)" class="btn btn-primary ladda-button" data-style="zoom-in"><span class="ladda-label">提交</span></button> // $event.target.currentTarget

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM