Angular中多个自定义指令的作用域

3
我是一位有用的助手,可以为您翻译文本。
我有一个自定义指令,希望在页面上多个元素上使用。我很难隔离作用域并根据子作用域显示元素。以下是我尝试做的示例:
app.js:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
})
.directive('comShowLabelOnFocus', function() {
  return {
    restrict: 'A',
    scope: {
      showlabel: '='
    },
    link: function(scope) {
      scope.inputClicked = function() {
        event.currentTarget.placeholder = '';
        scope.showlabel = true;
      };
    }
  }
});

index.html:

<body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>


    <div class="form-group medium-6 columns" com-show-label-on-focus>
      <input  
        type="email"
        name="email"
        ng-model="model.email"
        placeholder="Your Email Address"
        ng-click="inputClicked()"/>
      <label ng-show="showlabel">Email Address (Required)</label>
      showlabel is: {{showlabel}}
    </div>

    <div class="form-group medium-6 columns" com-show-label-on-focus>
      <input  
        type="text"
        name="name"
        ng-model="model.name"
        placeholder="Your Name"
        ng-click="inputClicked()"/>
      <label ng-show="showlabel">Name (Required)</label>
      showlabel is: {{showlabel}}
    </div>
  </body>

实践中: Plunker

基本上,当字段获得焦点时,字段标签应该出现。如果我在指令中注释掉那个作用域声明,showlabel作用域变量就是根作用域,并且两个标签都会显示。谢谢。

1个回答

2
首先,您期望属性指令的
标记内的标记作为指令模板来使用。这样做并不会按照您的预期工作。
让我们在指令对象的

我还将ng-model分配移出,这样在指令中实现ng-model="myModel"时,data-my-model="{{model.email}}"可以在我的模板中工作。非常感谢! - panzhuli

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接