Douglas Gaskell Douglas Gaskell - 6 months ago 11
HTML Question

Two custom elements via directives, only one is rendered on the page

I have two directives that define two elements I want to use on my page. If I use both directives on the page only the first one is rendered. I'm sure I'm breaking some rule of angular, not sure what though.

Directives:

//The template and handler for the set username button
chatApp.directive('setUsernameButton', ['username', function(username){
function link(scope, element, attrs){
element.bind('click', function(){
username.setUsername();
scope.$parent.$apply();
});
};
var template = '<div ng-disabled="username.invalidUsername" ng-class="{disabled: username.invalidUsername}" id="setNameButton" class="ui teal button">Set Name</div>'
return {
restrict: 'E',
replace: true,
template: template,
link: link,
scope: false
};
}]);

//The template and handler for username input field
chatApp.directive('usernameInputField', ['username', function(username){
function link(scope, element, attrs){
element.bind('keydown', function(e){
if(e.keyCode == 13){
username.setUsername();
scope.$parent.$apply();
}
});
};
var template = '\
<div class="ui input">\
<input ng-model="username.name" type="text" placeholder="Username...">\
</div>'
return {
restrict: 'E',
replace: true,
template: template,
link: link,
scope: false
};
}]);


HTML Snippet:

<div ng-if="!username.nameSet" class="ten wide column">
<set-username-button />
<username-input-field />
</div>

Answer

If you use the directive as an attribute, both the directives show up properly. If you want to use it as an element, it will work if you wrap your directive elements inside a div. Both ways work. Use it however you like

demo

<div set-username-button></div>
<div username-input-field></div>

or you could do this

  <div>
      <set-username-button />
  </div>
  <div>
    <username-input-field /> 
  </div>
Comments