1

I've created a custom directive in AngularJS. In the link function I'm adding the ng-model and ng-options attributes to the inner template, but, unfortunately the binding doesn't work. But when I place the inner template as is into my html file all works well.

application.directive("customSelect", function () {
var directive = {
    restrict: 'E',
    template: '<select name="ArrDeplocation" class="arrdepSelect"></select>',
    link: function (scope, elem, attr) {
        console.log('scope: ', scope);
        console.log('element: ', elem);
        console.log('attribute: ', attr);

        $(elem.children()[0]).attr('ng-model', 'model.selectedCity');
        $(elem.children()[0]).attr('ng-options', 'city for city in model.cities');

        $(elem.children()[0]).selectmenu();

    }
};
return directive;
});
1
  • 1
    Tried, it throws and exception, saying $apply is in process Commented Apr 25, 2013 at 7:32

2 Answers 2

3

I don't understand why you need to set attributes in the link func. You can simply put into your template.

http://plnkr.co/edit/9u6nkLYKHxBBiJ60mpbF?p=preview

app.directive("customSelect", function () {
  var directive = {
    restrict: 'E',
    template: '<select name="ArrDeplocation" class="arrdepSelect"'
     + 'ng-model="model.selectedCity" ng-options="city for city in model.cities">    </select>',
    link: function (scope, elem, attr) {
      // run jquery mobile methods here...
    }
  };
  return directive;
});

You may want to elaborate what you really want to achieve here.

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to modify your template in the link function, then you must recompile it.

Solution: http://plnkr.co/edit/bpiqXdQe91RJBaJXTPXO?p=preview

app.directive("customSelect", function ($compile) {
  return {
    restrict: 'E',
    template: '<select name="ArrDeplocation" class="arrdepSelect"></select>',
    link: function (scope, elem, attr) {
      elem.find('select').attr({
        'ng-model':   'model.selectedCity',
        'ng-options': 'city for city in model.cities'
      });
      var tpl = elem.html();
      elem.html($compile(tpl)(scope));
      elem.find('select').selectmenu();
    }
  };
});

The $compile("html string") compiles the template into:

a link function which is used to bind template (a DOM element/tree) to a scope

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.