我刚刚在几天前开始使用myApp示例与AngualrJS(爱好它),但我还没有完全掌握一些事件时序。AngularJS与控制器,AJAX,ng-repeat和指令的时序问题
我有一个路由器启动一个templateURL和一个控制器。 templateURL是一个使用ng-repeat来循环使用控制器加载的JSON的部分。如果控制器包含静态JSON似乎工作,我打算,但是当我加载使用$ JSON的HTTP我开始跑步进入时机的问题:
- 的$ HTTP回报的事情像扔一个404之前的部分解释图像路径,然后才能被替换 - >“{{album.thumbnail}} jpg”
- 我也有一个指令,在控制器启动异步$ http调用后触发一次,并在$ http调用实际完成后再次触发控制器(理想情况下,我只希望它在$ http完成后触发一次)
我的意图是使用检索使用ng-repeat通过$ http专辑JSON数据循环播放模板以构建我的图库。一旦完成循环,我想调用一个最终的功能,让画廊有一个类似Pinterest的砌体布局。这看起来像是一个非常典型的流程($ http - > ng-repeat - > final函数),所以在这一点上我必须缺少一些小东西。
期待更多地了解AngularJS ...
HTML
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<title>myApp</title>
</head>
<body>
<div ng-view></div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.5/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.5/angular-route.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="js/modernizr-transitions.js"></script>
<script src="js/jquery.masonry.min.js"></script>
</body>
</html>
模块
angular.module('myApp', [
'ngRoute',
'myApp.filters',
'myApp.services',
'myApp.directives',
'myApp.controllers'
])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/gallery', {templateUrl: 'gallery.html', controller: 'ctrlGallery'});
$routeProvider.otherwise({redirectTo: '/gallery'});
}]);
控制器
angular.module('myApp.controllers', [])
.controller('ctrlGallery', ['$scope', '$http', function (lcScope, lcHttp) {
lcHttp.get("/services/gallery.php?start=1&count=12")
.success(function(data, status, headers, config) {
lcScope.albums = data.DATA;
})
}]);
指令
angular.module('myApp.directives', [])
.directive('postGalleryRepeatDirective', function() {
return function (scope, element, attrs) {
if (scope.$last) {
$('#container').masonry({
itemSelector: '.box',
columnWidth: 250,
isAnimated: !Modernizr.csstransitions,
isFitWidth: true
});
}
};
});
gallery.html部分
<div class="masonry" ng-controller="ctrlGallery">
<div class="box masonry-brick" ng-repeat="album in albums" post-gallery-repeat-directive>
<a href="{{ album.link }}">
<img src="/img/{{ album.thumbnail }}.jpg">
</a>
<p>{{ album.name }}</p>
</div>
</div>