【发布时间】:2016-07-23 05:06:13
【问题描述】:
我有一个包含很多表单元素的 Angular 应用程序。在“编辑”模式下,用户可以编辑输入项、更改选项、标记复选框等。在“读取”模式下,应该只能读取这些值。只有管理员可以编辑页面上的任何内容,其他人只能阅读内容。
我想做的只是让脚本在只读模式下使用纯 span 或 div 元素,以减少整体观察者的数量。在实现方面,我总是不得不定义两个单独的 html '块',如下所示。
exampleInput.tpl.html
注意:我在这里使用ng-if,因为我想以只读模式从DOM中删除输入元素,以减少观察者的数量。
<!-- editable mode. -->
<input
ng-if="!$ctrl.isReadOnly()"
ng-model="$ctrl.value"
value="$ctrl.value"
/>
<!-- read only -->
<span
ng-if="$ctrl.isReadOnly()"
ng-bind="$ctrl.value">
</span>
exampleInput.comp.js
// The example-input component
(function(){
"use strict";
angular
.module("exampleInput", ["ngSanitize", "userSettings"])
.component("exampleInput", {
templateUrl: "exampleInput.tpl.html",
bindings: {
value: "="
},
transclude: true,
controller: ["$scope", "userSettings", function($scope, userSettings){
var ctrl = this;
ctrl.isReadOnly = userSettings.isReadOnly;
}
]
});
}());
应用程序:
<qa-input value="value.foobar">
</qa-input>
我的问题:
有没有更好的方法呢?我知道我可以只有一个输入元素并使用 css 来控制“禁用”模式下的样式,但这不会删除观察者,这是我这样做的主要原因。我对 Angular 还很陌生,所以任何建议都值得赞赏。
我正在使用 Angular 1.5.x。
【问题讨论】:
-
你可以使用something like this 吗?它已经拥有
enable / disable和许多其他功能。我将它用于我的一个应用程序,它可以节省大量时间。 -
哦,哇,我什至不知道这存在!感谢您指出!