0
我有一個指令來渲染具有某些特定值的select元素。下面是代碼:帶有隔離範圍的AngularJS窗體控制指令
該指令的模板:
<select id="{{name}}"
class="form-control"
ng-model="selectedOption"
ui-jq="selectpicker"
ui-options='{ iconBase: "famfamfam-flag", tickIcon: "fa fa-check" }'>
<option ng-repeat="o in data" value="{{o.id}}">{{o.label}}</option>
指令代碼:
(function() {
appModule.directive('yesNoDeclineCombo', ['$timeout',
function ($timeout) {
return {
restrict: 'E',
replace: true,
templateUrl: '/yesNoDeclineCombo.cshtml',
scope: {
selectedOption: '=?',
name: '@'
},
link: function ($scope, element, attrs) {
$scope.data = app.consts.yesNoDeclineData;
$scope.data.unshift({ id: null, label: 'Not Assigned' });
//refresh combo
$timeout(function() {
$(element).selectpicker('refresh');
});
$scope.$watch('selectedOption', function (newValue) {
$timeout(function() {
$(element).selectpicker('refresh');
}, 0);
});
}
};
}
]);
})();
標記使用:
<yes-no-decline-combo selected-option="vm.specialDietId"
ng-required="vm.isFieldRequired('SpecialDiet')" name="SpecialDiet">
</yes-no-decline-combo>
標記渲染:
<select id="SpecialDiet" class="form-control ng-pristine ng-untouched ng-isolate-scope ng-empty ng-invalid ng-invalid-required" ng-model="selectedOption" ui-jq="selectpicker" ui-options="{ iconBase: "famfamfam-flag", tickIcon: "fa fa-check" }" selected-option="vm.specialDietId" ng-required="vm.isFieldRequired('SpecialDiet')" name="SpecialDiet" required="required" tabindex="-98">
<!-- ngRepeat: o in data --><option ng-repeat="o in data" value="" class="ng-binding ng-scope" selected="selected">Not assigned</option><!-- end ngRepeat: o in data --><option ng-repeat="o in data" value="1" class="ng-binding ng-scope">Yes</option><!-- end ngRepeat: o in data --><option ng-repeat="o in data" value="2" class="ng-binding ng-scope">No</option><!-- end ngRepeat: o in data --><option ng-repeat="o in data" value="3" class="ng-binding ng-scope">Decline To Answer</option><!-- end ngRepeat: o in data -->
我如何將能夠使該指令使NG-模型:
ng-model="vm.specialDietId"
,而不是
ng-model="selectedOption"
我之所以需要這個行爲是因爲另一個屬性指令,讀取的ngModel綁定的模型屬性並執行一些其他功能。
感謝
當我使用範圍時會發生什麼變化:true?謝謝 – Bill
@Bill你的'$ scope'不會被隔離:http://stackoverflow.com/a/28867992/3368498 –