两个自定义元素通过指令,只有一个在页面上呈现

时间:2016-05-08 06:37:41

标签: javascript html angularjs angularjs-directive

我有两个指令定义了我想在页面上使用的两个元素。如果我在页面上使用这两个指令,则只渲染第一个。我敢肯定我打破了一些角度规则,但不确定是什么。

指令:

  //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代码段:

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

1 个答案:

答案 0 :(得分:2)

如果您将该指令用作属性,则两个指令都会正确显示。如果要将它用作元素,如果将指令元素包装在div中,它将起作用。两种方式都有效。无论你喜欢使用它

demo

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

或者你可以这样做

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