我现在已经做了3天的angularjs,现在我对控制器和指令感到困惑。
我有一种情况需要根据从选择列表中选择的选项显示值。此值需要显示在页面的一部分上,该部分不在显示选择列表的控制器中。
有可能这样做吗?如果是这样,谁能告诉我怎么样?代码示例将受到欢迎。我无处可去。
据我所知,到目前为止,该指令与控制器有关,所以我想做的事情似乎不可能(至少使用这种方法)。
例如:
<div ng-controller="AppCtrl">
<!-- list of credit cards -->
<select ng-model="myOption" ng-change="selectAction()" ng-model="creditCards">
<option ng-repeat="creditcard in creditCards" value="{{creditcard.value}}">{{creditcard.name}}</option>
</select>
</div>
<div ng-controller="BasketCtrl">
<!-- the card charge shown here is based on the option selected -->
<div data-card-charge></div>
<div>
答案 0 :(得分:1)
使用$rootScope
。
像这样:http://plnkr.co/edit/S3FjxPggoWPUGqkbs7fb?p=preview
<强> JS:强>
app.controller('AppCtrl', function($scope, $rootScope) {
$scope.creditCards = [
{
name: "Visa"
},
{
name: "Mastercard"
}
];
$scope.updateValue = function (creditCard) {
$rootScope.$broadcast('cardChanged', {card: creditCard });
};
});
app.controller('BasketCtrl', function($scope, $rootScope) {
$rootScope.$on('cardChanged', function( data, args) {
$scope.cards = args.card;
});
});
<强> HTML:强>
<div ng-controller="AppCtrl">
<!-- list of credit cards -->
<select ng-model="myOption" ng-change="updateValue(creditCards)" ng-model="creditCards">
<option ng-repeat="creditcard in creditCards" value="{{creditcard.value}}">{{creditcard.name}}</option>
</select>
</div>
<div ng-controller="BasketCtrl">
<!-- the card charge shown here is based on the option selected -->
<div data-card-charge></div>
<p ng-repeat="card in cards">{{ card.name }}</p>
<div>
答案 1 :(得分:1)
您也可以使用工厂存储您选择的设置。有点像这样:
.factory('SelectedCreditCard', function ($timeout) {
var _service, _data;
_service = {};
_data = {
selected: undefined
};
_service.setSelected = function (card) {
_data.selected = card;
};
_service.getSelected = function () {
return _data;
};
return _service;
});
然后你可以使用SelectedCreditCard.setSelected(卡片)保存选定的卡片,但由于你使用带有ng-model的选择我们甚至不需要这样做,因此Angular负责繁重的工作:
<强>控制器:强>
.controller('SetController', function($scope, SelectedCreditCard) {
$scope.creditcard = SelectedCreditCard.get();
})
查看:强>
<div ng-controller="SetController">
<select ng-model="creditCard.selected" ng-options="card.name for card in creditCards"></select>
</div>
要在指令中使用所选卡,您可以简单地将SelectedCreditCard工厂注入指令中。更简洁的方法是将数据发送到BasketCtrl的范围,并将其用作指令的表达式:
<div ng-controller="BasketCtrl">
<div data-card-charge="creditCard"></div>
<div>
同时强> 您在选择中有两个ng-model:)