我有一个Parent Angular Controller,它有一个需要与其他控制器共享的方法。父控制器如下所示:
"use strict";
(function() {
var ParentCtrl = function($scope, atomico, Asset) {
var _this = this;
_this.busy = atomico.identity == null;
_this.oldestTimestamp = null;
_this.assets = [];
/**
* Infinite scrolling, fetches more assets when the user scrolls down.
*/
_this.fetch = function() {
if (_this.noMoreAssets) { return; }
_this.busy = true;
Asset.all(atomico.metadata['campaign'].id, _this.oldestTimestamp, $scope.dates.start, $scope.dates.end, function(assets) {
_this.busy = false;
if (assets.length > 0) {
_this.assets = _this.assets.concat(assets);
_this.oldestTimestamp = moment(assets[assets.length - 1].start).unix();
} else {
_this.noMoreAssets = true;
}
});
};
};
ParentCtrl.$inject = [ '$scope', 'atomico', 'Asset' ];
angular.module('myModule').controller('ParentCtrl', ParentCtrl);
})();
我将此控制器扩展到另一个控制器中,以便在视图中无限滚动。这是子控制器:
"use strict";
(function() {
var ChildCtrl = function(atomico, userState, $controller, $scope) {
var _this = this;
angular.extend(_this, $controller('ParentCtrl', {$scope: $scope}));
// Fetch assets after user, campaign and account data is available.
atomico.ready(function(){
var dates = userState.getCampaignViewData(atomico.metadata['campaign'].id).list_view;
$scope.dates = _.isEmpty(dates) ? {start: moment(), end: moment()} : dates;
_this.busy = false;
});
};
CampaignListCtrl.$inject = [ 'atomico', 'userState', '$controller', '$scope' ];
angular.module('myModule').controller('ChildCtrl', ChildCtrl);
})();
在我看来,我有这个:
<div id='agenda_viewer' ng-controller="ChildCtrl as ctrl">
<p class="at-text-center at-block-center c-empty-list" ng-hide='ctrl.assets.length || ctrl.busy'>
There are no assets to show for this day
</p>
<div class="agenda-flight__content at-row" infinite-scroll='ctrl.fetch()' infinite-scroll-disabled='ctrl.busy' infinite-scroll-parent="true">
<div class="agenda-flight at-row agenda-asset__live" ng-repeat='asset in ctrl.assets' ng-init='asset.collapsed = false'>
<directive-list-row asset='asset'></directive-list-row>
<directive-list-expanded asset='asset' ng-if='asset.collapsed'></directive-list-expanded>
</div>
</div>
<div class='c-loading' ng-show='ctrl.busy'>Loading data...</div>
</div>
我遇到的问题是,即使服务返回数据,ctrl.assets也总是为空。这是ctrl.assets在父控制器中定义而在子控制器中不可见的问题吗?如何让资产对象共享给子控制器,以便我可以在UI中看到数据?
答案 0 :(得分:0)
我最终做的是将一些控制器变量移到$scope
中,现在看起来效果很好。儿童共享$scope