I've got a very simple directive I'm working with - it's a small wrapper around a dropdown. I want to expose an attribute, "selectedOption" (well, selected-option) from it that I can two-way bind to the controller. I've set the property in the scope of the directive (and set it to = which I thought would allow the two-way binding), then exposed a property on the main controller.
I've attached an example. I would have expected that the default item shown would be "Beta". And if I changed selections to Alpha, the Controller value would be updated to "A". But that doesn't happen - they appear to be isolated even though I've specified that this property should be available to the controller.
What magic bit of code am I missing here?
angular
.module('app', []);
angular.module('app').controller('test', function(){
var vm = this;
vm.inv = 'B';
vm.displayInv = function () {
alert('inv:' + vm.inv);
};
});
angular.module('app')
.directive('inventorytest', function () {
return {
restrict: 'E',
template: '<select ng-model="ctrl.selectedOption" ng-options="inv.code as inv.desc for inv in ctrl.invTypes"></select>{{ctrl.sample}}. Selected: {{ctrl.selectedOption}}',
scope: { selectedOption: '='},
controller: function () {
this.invTypes = [
{ code: 'A', desc: 'Alpha' },
{ code: 'B', desc: 'Bravo' },
{ code: 'C', desc: 'Charlie' },
];
this.sample = 'Hello';
},
controllerAs: 'ctrl'
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js"></script>
<div ng-app="app" ng-controller="test as vm">
<inventorytest selected-option='vm.inv'></inventorytest>
<button ng-click="vm.displayInv()">Display</button>
<br/>
Controller: {{vm.inv}}
</div>
答案 0 :(得分:2)