0

I'm trying to add an attribute directive to a select that is using ng-options:

<select ng-model="item.Subcategory" ng-options="subcategory.Name as subcategory.Name for subcategory in GetSubcategories(item.Category)" monitor></select>

At the moment, it doesn't do anything meaningful:

angular.module("monitor", [])
.directive("monitor", function()
{
    var directive =
    {
        restrict: "A",
        scope:
        {
        },
        controller: function($scope)
        {
            console.log("I exist");
        }
    };

    return directive;
});

The directive it seems to be working, as I see an "I exist" per item that uses the directive, but it select loses its options.

With the directive in place, I can see this in the HTML as the only option for the select:

<option value="?" selected="selected"></option>

As opposed to this, when not using the directive:

<option value="0" selected="selected">Cats</option>
<option value="1">Dogs</option>

Why might my directive be breaking ng-options?

Thank you.

3

1 Answer 1

0

There are potentially several issues here, either of which could be the cause of the problem.

According to the AngularJS Developer Guide on Directives:

If multiple directives on the same element request a new scope, only one new scope is created.

You are creating a new isolate scope on your directive which is likely overriding the scope for the other directives, including ng-options.

Also, you should keep in mind that the controller argument creates a new controller that is shared with other directives:

Controller constructor function. The controller is instantiated before the pre-linking phase and it is shared with other directives (see require attribute). This allows the directives to communicate with each other and augment each other's behavior.

Unless you want to use your directive to share data with other directives, you should probably avoid creating a controller.

Is there any reason why your directive can't accomplish what it needs to do in a simple link function?

1
  • Controllers in directives aren't just for sharing data with other directives. Their function is pretty much the same as a regular application controller: to provide behavior for the directive. The link function is, by definition, the place where DOM manipulation should be done. Aug 24, 2013 at 4:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.