Calvin
Calvin

Reputation: 8765

Angular $compile on scope with ng-repeat doesn't work

I have a directive that uses the $compile service to generate a template. It won't generate the select options using ng-options or ng-repeat, even though I clearly have the users array set in my scope. Why doesn't this work? This just gives me a blank <select> field with no options.

angular.module("myApp").directive("selectForm", [
  '$compile',
  function($compile) {
    return {
      restrict: 'C',
      scope: true,
      link: function(scope, element, attrs) {

        scope.users = [
          { id: 1, name: "User 1" },
          { id: 2, name: "User 2" }
        ];

        element.on('click', function(e) {

          var selectHtml = $compile('\
            <select\
              class="col-lg-2 form-control"\
              ng-options="user.id as user.name for user in users">\
            </select>\
          ')(scope);

          $(element).html(selectHtml);
        });

      }
    }
  }

]);

Upvotes: 1

Views: 1209

Answers (1)

Khanh TO
Khanh TO

Reputation: 48972

There is something to change in your code to make it work:

  • <select> works only when you also supply ng-model
  • Wrap your code inside scope.$apply.
  • Call element.off("click") to unsubscribe to the event to avoid flickering.

DEMO

Upvotes: 3

Related Questions