Why isn't my directive's selection being bound to the controller?

时间:2015-10-30 22:44:25

标签: angularjs angularjs-directive

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>

1 个答案:

答案 0 :(得分:2)

By default, Angular creates a scope object (most commonly referred to with the variable $scope) for each HTML Template. The scope: { selectedOption: '='}, in your code is actually creating an isolated scope for the directive, and making selectedOption a property on that scope object. The line controllerAs: 'ctrl' is creating a property on this same scope object which points to the controller object. This actually means that in the controller, you could technically access ctrl.$parent.selectedOption, which would return the selectedOption property of the ctrl object's parent, which is scope. In practice, however, this is very cumbersome. In Angular 1.3, a new option was added, bindToController : true. This option automatically binds the properties from the scope: definition to the controllerAs: object instead of scope itself.