我正在尝试做类似于this fiddle的事情。
我期望发生的是显示选择列表,当选择其中一个选项时,此行代码中会显示true
或false
这个词:
<span data-ng-bind="cardType.transactionFee"></span>
当卡片类型发生变化时,$watch
部分作为警告显示hey, cardType has changed!
。
如何将更改的值传递给directive
?
.controller('AddCreditCardChargeCtrl', ['$scope', function($scope) {
$scope.creditCards = [
{ name: 'VISA DEBIT/DELTA', value: 'DEL', transactionFee: false},
{ name: 'VISA CREDIT', value: 'VIS', transactionFee: true },
{ name: 'MASTERCARD CREDIT', value: 'MSC', transactionFee: true },
{ name: 'MASTERCARD DEBIT', value: 'MCD', transactionFee: false },
{ name: 'MAESTRO', value: 'MAE', transactionFee: false },
{ name: 'SWITCH', value: 'SWI', transactionFee: false },
{ name: 'VISA ELECTRON', value: 'ELC', transactionFee: false },
{ name: 'SOLO', value: 'SOL', transactionFee: false }
];
$scope.selectAction = function() {
alert($scope.creditCardModel);
alert(hasTransFee($scope.creditCardModel));
$scope.cardType=hasTransFee($scope.creditCardModel);
// console.log(cardType.name)
// console.log(cardType.transactionFee)
console.log('watch')
$scope.$watch("cardType.transactionFee", function() {
alert('hey, cardType has changed!');
});
}
var hasTransFee = function(cardType)
{
for (var i=0; i < $scope.creditCards.length; i++) {
if($scope.creditCards[i].value==cardType && $scope.creditCards[i].transactionFee == true){
return true;
}
}
return false;
}
}])
.directive('bhtDiscountPrice',['BasketFactory',
function(BasketFactory){
return{
restrict:'EA',
scope:true,
link:function(scope,elem,attrs){},
template:'<span data-ng-bind="cardType.transactionFee"></span>'
}
}])
答案 0 :(得分:0)
scope: false
,因此根本没有新的范围,因此您将与控制器共享范围
有关编写自定义指令时使用范围的最佳方法,请查看When writing a directive in AngularJS, how do I decide if I need no new scope, a new child scope, or a new isolated scope?
尝试此操作,而不使用link
函数
.directive('bhtDiscountPrice',['BasketFactory',
function(BasketFactory){
return {
restrict: 'EA',
scope: true,
template:'<span data-ng-bind="cardType.transactionFee"></span>'
};
});