Angular: 遇到的一些坑
Angular應該很多人都已經(jīng)很了解,谷歌的MVW開源項目嚣崭。可能現(xiàn)在很多人開始鼓吹React了懦傍,但是它的成熟度還是沒法和Angular比雹舀,Angular足夠的強大去撐起很多項目。Angular已有豐富的教程和論壇社區(qū)粗俱。所以说榆,現(xiàn)在使用的話,還是學一點Angular好。
angular-resource
現(xiàn)在越來越流行用Rest服務签财,還用SOAP確實有點out串慰。所有后端數(shù)據(jù)都可以做成服務。angular的雙向綁定連接的方法有很多唱蒸,其中一種就是angular-resource邦鲫。使用挺方便,當然也有一些坑神汹。
具體操作看教程或者AngularJS Resource:與 RESTful API 交互庆捺,剛開始用起來很爽。三個文件如下:
app.js
angular.module('moviesApp', [
'moviesServices'
]);
movieController.js
angular
.module('moviesApp')
.controller('moviesController', moviesController);
moviesController.$inject = ['$scope', 'Movies'];
function moviesController($scope, Movies) {
$scope.movies = Movies.query();
}
movieService.js
var moviesServices = angular.module('moviesServices', ['ngResource']);
moviesServices.factory('Movies', ['$resource',
function ($resource) {
return $resource('/api/movies/', {}, {
query: { method: 'GET', params: {}, isArray: true }
});
}]);
服務就是將API的數(shù)據(jù)查詢出來屁魏,你也可以完成增刪查改的動作滔以。Controller
調(diào)用一下就OK。
坑一:
想在js端獲取某個$resource
返回的數(shù)據(jù)氓拼,它與$http.get()
不一樣你画,數(shù)據(jù)有所封裝。所以不好直接獲取數(shù)據(jù)桃漾。參考從Angularjs-Resource獲取數(shù)據(jù)一文撬即,這時,需要做個Callback函數(shù)呈队,將數(shù)據(jù)調(diào)出來。
$scope.profileslist = profilelist.query(function(response) {
angular.forEach(response, function(item) {
if (item.profileid) {
$scope.items.push(item.profileid);
}
});
});
坑二:
當ng-repeat數(shù)據(jù)加載完成觸發(fā)事件唱歧,參考ng-repeat加載完成事件一文宪摧,當然循環(huán)器中,需要標簽my-repeat-directive
颅崩,在加載完成后就會觸發(fā)該事件几于。
angular.module('myApp', []).directive('myRepeatDirective', function() {
return function(scope, element, attrs) {
angular.element(element).css('color', 'blue');
if (scope.$last) {
window.alert("im the last!");
}
};
})
轉載,請表明出處沿后。總目錄前端經(jīng)驗收集器