0

我想创建/使用 AngularJS 指令来避免创建一些多余的 HTML,并简化我使用 Bootstrap 元素的方式。我想以这种方式使用指令:

<myDirective id="person.lname" label="Last Name"></myDirective>

我希望 AngularJS 编写的模板是:

<label for="person.lname">Last Name</label>
<input id="person.lname" name="person.lname" ng-model="person.lname">

我将如何声明一个指令以能够创建此模板并让与 ng-model 的绑定仍然有效?有什么理由说明这不是一个好主意吗?

谢谢。

更新

我添加了标签标签以反映 id/name 将如何用于输入元素。生成的模板将允许您单击标签并将焦点放在输入元素上。

4

1 回答 1

1

这应该做你想要的:

.directive('myDirective', function() {
  return {
    scope: {
      model: '=identifier',
      id: '@identifier',
      label: '@',
    },
    restrict: 'E',
    template: '<label for="{{id}}">{{label}}</label><input id="{{id}}" name="{{id}}" ng-model="model">'
  };
})

看法:

<my-directive label='Last name' identifier="person.lname"></my-directive>

Fiddle

于 2014-04-24T21:57:14.817 回答