Kohjah Breese
Kohjah Breese

Reputation: 4136

Set angularjs directive attribute from a controller

I'm using the Angular Bootstrap typehead directive, which can be configured from HTML like so:

<div ng-controller="search">
  <input typeahead-focus-first="false" />
</div>

Is it possible to set the 'typeahead-focus-first' attribute from the ng-controller instead?

Upvotes: 0

Views: 517

Answers (2)

Joe Enzminger
Joe Enzminger

Reputation: 11190

If your controller scope has a property

$scope.typeahead = true;

then

<div ng-controller="search">
  <input ng-if="typeahead" typeahead-focus-first="false" />
  <input ng-if="!typeahead" />
</div>

or

<div ng-controller="search">
  <input typeahead-focus-first="typeahead" />
</div>

The second method requires your typeahead directive to be able to parse the typeahead expression. There are several ways to accomplish this (isolated scope or $parse for example). The typeahead directive in angular bootstrap does this for you, so the second method should work.

EDIT: As a directive

.directive('search', function() {
    return {
        restrict: 'E',
        template: '<div><input typeahead-focus-first="false" /></div>',
        scope: true,
        controller: function($scope) {
        },
        link: function(scope, element, attrs) {
            //this is where you want to do your DOM manipulation (if any)
        }
    };
})

Usage:

<search></search>

Upvotes: 2

ntrp
ntrp

Reputation: 401

the typeahead property is evalued from attr with this expression:

var focusFirst = originalScope.$eval(attrs.typeaheadFocusFirst) !== false;

so you should set a variable in your scope

$scope.typeahead = true;

and then

<div ng-controller="search">
    <input typeahead-focus-first="{{typeahead}}" />
</div>

Typeahead source here.

EDIT: As has emerged from the comments seems you want to edit the behaviour from the controller without writing anything on the dom. Unfortunately I think this is not possible because the variable governing that behaviour is saved inside the closure at compile time and is not modificable after the component has been linked. You need to recompile the component to change that behaviour with, for example an ng-if.

Upvotes: 1

Related Questions