这是一个困惑:我有一个基本的单页 Angular 应用程序,我正在其中构建我的作品集。在 Controller 中,我有 3 个 Controller ,而项目是我遇到问题的 Controller 。
我正在使用 ng-repeat 来获取列表中的每个项目。然后我通过 JavaScript 来定位它们以正确调整它们的大小。
问题是它根本不调整它们的大小。即使我按照建议使用 $viewContentLoaded ,它们也不会在 JW.core 运行之前加载。因此它们是 0px x 0px,而不是 500 x 500。
我知道这一点,因为如果我在 JW.core 内的调整大小函数调用上设置超时,那就没问题了。然后每个项目都被重复并可以相应地调整大小。
我还认为,由于我对 Angular 还很陌生,所以我可能做错了什么。
Controller .js:
function mainCtrl($scope) {
}
function projectsCtrl($scope, $http) {
$http.get('data/projects/projects.json').success(function(data) {
$scope.projects = data;
});
$scope.$on('$viewContentLoaded', function () {
new JW.core();
});
}
function aboutCtrl($scope, $http) {
$http.get('data/about/about.json').success(function(data) {
$scope.about = data;
});
}
核心.js:
var JW = JW || {};
JW.core = function() {
var initialise = function () {
new JW.elementDimensions();
};
initialise();
};
elementdimensions.js:
var JW = JW || {};
JW.elementDimensions = function () {
var scrollbarWidth,
resizeDim = function (e, ww, wh) {
var wh = window.innerHeight;
$(e).width(ww + 'px');
$(e).height(wh + 'px');
},
initialise = function () {
var ww = window.innerWidth - scrollbarWidth,
$targets = $('#projects').find('.project');
$('.project-wrapper').width((window.innerWidth - scrollbarWidth) * $targets.length);
$('.project-wrapper').height(window.innerHeight);
_.each($targets, function(e) {
resizeDim(e, ww);
console.log(e);
})
};
initialise();
$(window).on('resize', function() {
initialise();
});
return this;
};
和 View :
<div class="project" ng-repeat="project in projects">
<div class="project-img" style="background: url('{{project.imageUrl}}') fixed;" id="{{project.id}}">
<div class="info-container">
<h1>{{project.title}}</h1>
<p class="description">
{{project.description}}
</p>
<div class="tags">
<ul>
<li ng-repeat="tag in project.tags">{{tag}}</li>
</ul>
</div>
<a class="goto" href="{{project.link}}">{{project.linktext}} →</a>
</div>
</div>
</div>
最佳答案
您需要做的是在您的路线上使用resolve。
$routeProvider.when('/products', {
templateUrl: 'products.html',
controler: 'productsCtrl',
resolve: {
products: ['$http', '$q', function($http, $q){
var deferred = $q.defer();
$http.get('data/projects/projects.json').success(function(data) {
deferred.resolve(data);
});
return deferred.promise;
}]
}
});
然后,在您的 Controller 中,注入(inject) $scope 和 products 而不是 $scope 和 $http,除非 Controller 运行后您还需要 $http 来执行其他操作,在这种情况下只需添加产品即可。这本质上是延迟 Controller 的初始化,直到加载内容。
关于javascript - $viewContentLoaded 在 View 内容加载之前触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15054932/