重复使用具有不同数据模型的模板

时间:2017-05-29 15:39:11

标签: angularjs angular-ngmodel angular-directive

我正在使用Angular 1.4.7创建一个包含多个文本字段的表单。表单用于

  • (a)输入新数据或
  • (b)显示现有数据(只读)。

使用不同的数据模型输入和显示数据。

使用app.directive()

将表单分成小的子模板
app.directive('usedProducts', function() {
    return {
        restrict: 'E',
        templateUrl: 'used-products.html',
        scope: {
            readOnlyMode: '@'
        }
    };
});

使用表格输入数据:

<used-products></used-products>

使用表单显示数据(只读):

<used-products readOnlyMode="true"></used-products>

我的子模板的代码(used-products.html):

<div class="col-md-12">
  <textarea auto-height
    type="text" class="form-control"
    id="fooBar"
    ng-init="isReadOnly = (readOnlyMode.toLowerCase() === 'true' || false)"
    ng-model="isReadOnly ? my.readOnly.model.foo : my.other.enterData.model.fooBar"
    ng-readonly="isReadOnly"
    ng-attr-rows="isReadOnly ? '5' : '10'">{{readOnlyMode}}, {{isReadOnly}}</textarea>
</div>

上面的代码无效,所以请将其视为我的期望。基本上,我想根据传递给子模板的参数在ng-model的两个值之间切换。我还想根据值将textarea设置为readonlyrows仅用于调试目的。

如何重新使用具有不同数据模型的模板,如何使我的代码工作或有更好的方法?我是AngularJS的新手,到目前为止,这是我能提出的唯一想法。

//编辑:重新使用具有不同模型的模板对我来说无法解决问题,因此最终我最终复制了我的代码,以获得两个不同的模板,每个模板都引用了各个模型。< / p>

1 个答案:

答案 0 :(得分:0)

使用scope将属性绑定到指令

app.directive('usedProducts', function() {
    return {
        restrict: 'E',
        templateUrl: 'used-products.html',
        scope: {
            readOnly: '@readOnly'
        }
    };
});

因为ng-model是angular指令,所以不要使用任何花括号。也避免在ng-model内写表达式。或者你可以使用ng-init

<div class="col-md-12">
  <textarea auto-height
    type="text" class="form-control"
    id="fooBar"
    ng-init="my.model = (readOnly.toLowerCase() == 'true') ? my.readOnly.model.foo : my.other.enterData.model.fooBar"
    ng-model="my.model"
    ng-readonly="readOnly.toLowerCase() == 'true'"
    rows="{{ readOnly.toLowerCase() == 'true' ? 5 : 10 }}></textarea>
</div>