我有一个自定义指令:myContent
'use strict';
angular.module('myModule').directive('myContent', function() {
return {
restrict: 'E',
templateUrl: 'myContent.html',
controller: function($scope){
$scope.selectedContents = {
priceOrTransactionOption : null,
yearlyOrMonthly : 'Yearly',
contentIndicator : null
};
$scope.comboContent = {
priceOrTransactionOption : ['By Price Range', 'By Transactions'],
yearlyOrMonthly : ['Yearly', 'Monthly'],
contentIndicator : ['Active configuration', 'Next Configuration']
};
},
controllerAs: 'myContentCtrl'
};
});
而且我在多个地方使用相同的指令:
<div class="tab-content col-lg-10">
<my-content></my-content>
</div>
<div class="tab-content col-lg-10">
<my-content></my-content>
</div>
<div class="tab-content col-lg-10">
<my-content></my-content>
</div>
我的指令(myContent.html)的html页面有一些数据:
<div class="row no-left-padding">
<div class="col-lg-3 no-left-padding">
<select class="form-control" ng-model="selectedContent.priceOrTransactionOption"
ng-options="keyOption as keyOption for keyOption in comboContent.priceOrTransactionOption">
</select>
</div>
<div class="col-lg-3 no-left-padding">
<select class="form-control" ng-model="selectedContent.yearlyOrMonthly" ng-disabled = "true"
ng-options="interval as interval for interval in comboContent.yearlyOrMonthly">
</select>
</div>
<div class="col-lg-3 no-left-padding">
<select class="form-control" ng-model="selectedContent.contentIndicator"
ng-options="indicator as indicator for indicator in comboContent.contentIndicator">
</select>
</div>
</div>
但我的问题是,当我在一个指令中更改模型时,它会反射(reflect)在每个指令中。
如何使用相同的指令,并将每个指令映射到不同的模型?
我曾尝试在我的自定义指令中添加一个属性:
<div class="tab-content col-lg-10">
<my-content category="type1"></my-content>
</div>
<div class="tab-content col-lg-10">
<my-content category="type2"></my-content>
</div>
<div class="tab-content col-lg-10">
<my-content category="type3"></my-content>
</div>
但我仍然对我应该在哪里映射类别以获取孤立对象感到困惑。
最佳答案
您需要将隔离范围添加到指令中。这有效地允许它拥有自己的一组属性:
angular.module('myModule').directive('myContent', function() {
return {
restrict: 'E',
templateUrl: 'myContent.html',
scope: {
category:'='
},
controller: function($scope){
$scope.selectedContents = {
priceOrTransactionOption : null,
yearlyOrMonthly : 'Yearly',
contentIndicator : null
};
$scope.comboContent = {
priceOrTransactionOption : ['By Price Range', 'By Transactions'],
yearlyOrMonthly : ['Yearly', 'Monthly'],
contentIndicator : ['Active configuration', 'Next Configuration']
};
},
controllerAs: 'myContentCtrl'
};
});
然后,您可以使用上面的示例:
<div class="tab-content col-lg-10">
<my-content category="type1"></my-content>
</div>
每个人都将单独工作。
但请注意,当您添加隔离范围绑定(bind)“=”的属性时。有许多不同的类型,'@'、'=' 和 '&' 以及可选参数。范围属性的命名使用蛇形大小写。与其给你一个完整的解释,不如阅读 Angular developers guide on isolated scope
关于angularjs - 在可重用的 Angular 指令中隔离范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31156135/