Peter
Peter

Reputation: 1806

AngularJS Custom Directive isolated scope model binding

I'm trying to implement a double select list form component just to try out angular and try to understand it better.

The functionality of this directive is that the parent model contains the list of Available Items to choose from, and contains the destination list (selected) where chosen items are placed. When an item is chosen it will be removed from the available array and placed in the selected array.

As a form may require more than one of these double select list components I don't want to rely on hard coded property names but instead allow the lists to be passed in for two way data binding.

Here is a JSBin of the code: Double Select Lists

I haven't gone any further than just trying to bind the data to the lists via the passed in model property names.

On the directive, the following scope properties are defined. The availableItems and selectedItems should both be bound to the parent controllers properties. The highlightedAvailable and highlightedSelected are to store the user selections prior to the button clicks.

  scope: {
        availableItems: '=',
        selectedItems:  '=',
        highlightedAvailable: [],
        highlightedSelected: []
    },

Can someone please tell me why the controller properties never bind to the directive properties?

Thanks!

Upvotes: 0

Views: 403

Answers (2)

skeller88
skeller88

Reputation: 4504

To expand on aet's answer, the reason that the way you specified your directive attributes in your html did not work is because HTML is case-insensitive. So the 'availableItems' attribute was actually being passed to your directive scope as 'availableitems'. On the other hand, snake cased words like 'available-items' will be converted to camel case in your angular code.

That's the reason you write angular directives in the html as 'ng-repeat', 'ng-model', and so on, but in the angular source code you'll see these directive names camel cased: 'ngRepeat', 'ngModel'...

Be super careful to use snake-case in HTML, and camel case in your Javascript (Angular)! I've spent way too long on some bugs caused by that confusion.

Upvotes: 0

aet
aet

Reputation: 7292

First, you have an error being caused by your scope:

scope: {
    availableItems: '=',
    selectedItems:  '=',
    highlightedAvailable: [],
    highlightedSelected: []
},

should be:

scope: {
    availableItems: '=',
    selectedItems:  '='
},

Declare the arrays somewhere else, like in the link function:

link: function (scope, element, attrs) {
      scope.highlightedAvailable = [];
      scope.highlightedSelected = [];

The next problem was the way you specified the attributes to the directive, you had:

<div ng-Select-Lists availableItems='availableItems' selectedItems='selectedItems'>

Try this instead:

<div ng-Select-Lists available-items='availableItems' selected-items='selectedItems'>

Upvotes: 2

Related Questions