【发布时间】:2016-03-18 21:12:22
【问题描述】:
我有一个通过 RestAngular 加载对象数组的 MainController
controllers.controller('MainController', $scope, Restangular) {
$scope.colors = {};
Restangular.all('colors').getList().then(function(colors) {
angular.forEach(colors, function(c) {
c.brightness = getBrightness(c);
$scope.colors[c.id] = c;
});
});
};
我有一个路由来处理颜色的子页面。
$stateProvider
.state('picture', {
abstract: true,
url: "/picture/{pictureId:[0-9]{1,6}}",
templateUrl: "partials/picture.html",
controller: 'MainController'
}
)
.state('picture.colors', {
url: "/colors",
templateUrl: "partials/picture_colors.html",
controller: 'PictureColorsController'
}
);
在这里,我想要一个下拉菜单来多选颜色。
<multiselect ng-model="selector.colors"
options="c as c.name for c in colors| orderBy:'brightness'"
data-multiple="true"
header="Colors">
</multiselect>
这很好用。但是当页面加载时,我希望选择所有颜色。所以我想要的是这样的:
controllers.controller('PictureColorsController', $scope) {
$scope.selector = {colors:[]};
var selectAll = function() {
$scope.selector.colors.splice(0, $scope.selector.colors.length);
angular.forEach($scope.colors, function(c) {
$scope.selector.colors.push(c);
});
};
selectAll();
};
但是在执行子控制器“PictureColorController”时,颜色还没有加载。所以我能想到的唯一解决方案是跟随,但我并不喜欢它。感觉自己做错了什么。
controllers.controller('MainController', $scope, Restangular) {
$scope.colors = {};
var colorsCallback = undefined;
$scope.registerColorsCallbackFn = function(func) {
colorsCallback = func;
};
Restangular.all('colors').getList().then(function(colors) {
angular.forEach(colors, function(c) {
c.brightness = getBrightness(c);
$scope.colors[c.id] = c;
});
if (colorsCallback) {
colorsCallback();
}
});
};
和
controllers.controller('PictureColorsController', $scope) {
$scope.selector = {colors:[]};
var selectAll = function() {
$scope.selector.colors.splice(0, $scope.selector.colors.length);
angular.forEach($scope.colors, function(c) {
$scope.selector.colors.push(c);
});
};
selectAll();
$scope.registerColorsCallbackFn(selectAll);
};
有没有更清洁的方法来做到这一点?在我想要执行任何子控制器之前,我想在 MainController 中加载几个数据列表,所有这些数据都需要加载。有什么好的机制吗?
【问题讨论】:
标签: angularjs angularjs-scope restangular