下面是我的html代码,我在
中有一个方法moreThanOne.html
使变量
显示
为true因此它第一次加载one.html并调用我的控制器的init方法。但每当我再次更改show的值时,它都不会重新加载与one.html关联的控制器。
所以这里我的要求是,只要我点击与另一个控制器关联的按钮就会调用initiatePaymentCtrl的init()方法,以便在one.html上刷新数据
<div data-ng-if="data.length>1">
<div data-ng-include="'moreThanOne.html'"></div>
</div>
<div data-ng-if="data.length==1">
<div data-ng-controller="initiatePaymentCtrl" data-ng-include="'one.html'"></div>
</div>
<div data-ng-if="show">
<div data-ng-controller="initiatePaymentCtrl" data-ng-include="'one.html'"></div>
</div>
控制器
app.controller('initiatePaymentCtrl', function($scope, $http, paymentService) {
function init() {
alert('init');
var issuerId = paymentService.getIssuerId();
var paymentItemId = paymentService.getPaymentItemId();
$scope.paymentOptions = {};
if (typeof issuerId !== "undefined") {
paymentService.getPaymentOptions(issuerId,paymentItemId).then(
function(paymentOptions) {
$scope.paymentOptions = paymentOptions;
});
}
}
init();
$scope.initiateInitialPayment = function(){
paymentService.initiateInitialPayment();
}
});
我无法使用服务,因为有可能点击
时数据不会改变答案 0 :(得分:2)
你绝对应该使用服务。我不确定你的意思是什么意思:
我无法使用服务,因为有可能点击
时数据不会改变
如果您怀疑Angular在单击按钮时会执行摘要循环,您可以轻松地进行测试。摘要开始后,$scope
的更改应立即显示。
以下是一个简单消息服务的示例,可用于在控制器之间传递数据:
app.service("messageService", function() {
this._subscribers = [];
this.addSubscriber = function(sub) {
this._subscribers.push(sub);
};
this.sendMessage = function(message) {
var len = this._subscribers.length;
for (var i = 0; i < len; i++) {
this._subscribers[i].receive(message);
}
};
});
接收方可以订阅回复消息:
app.controller("responderController", function($scope, messageService) {
var numClicks = 0;
$scope.response = "";
$scope.data = [];
$scope.show = true;
$scope.stuff = "Stuff to show at first";
$scope.otherStuff = "Stuff to show for more than one";
$scope.oneStuff = "Stuff to show for one";
this.receive = function(message) {
if ($scope.show) {
$scope.show = false;
}
if (++numClicks > 2) {
$scope.data = [];
$scope.show = true;
numClicks = 0;
}
else {
$scope.data.push(message);
}
};
messageService.addSubscriber(this);
});
发件人可以使用该服务向所有订阅者发送消息:
app.controller("senderController", function($scope, messageService) {
$scope.sendClick = function() {
messageService.sendMessage("click");
};
});
这可以在HTML中使用,如下所示:
<div data-ng-controller="responderController">
<div data-ng-if="show">{{stuff}}</div>
<div data-ng-if="data.length > 1">{{otherStuff}}</div>
<div data-ng-if="data.length==1">{{oneStuff}}</div>
</div>
<button data-ng-controller="senderController" data-ng-click="sendClick()">Click</button>
你可以看到它working in a fiddle。
答案 1 :(得分:0)
使用从一个通信控制器继承的两个不同的控制器。虽然在我看来,在这种情况下使用指令会更好。
controller inheritance:
var app = angular.module('inheritance', []);
app.controller('ParentCtrl ', function($scope) {
});
app.controller('ChildCtrl', function($scope, $controller) {
$controller('ParentCtrl', {$scope: $scope});
});