如何在angularjs中显示和隐藏基于布尔值的元素属性

How to show and hide the element attribute based on boolean value in angularjs?

本文关键字:于布尔 属性 元素 隐藏 angularjs 显示      更新时间:2023-09-26

ctrl.js

在控制器中,如果用户登录编辑页面,则该值为true

var self = this;
self.edit = "true"

html

在添加页面上,它应该是

<md-input-container flex="25">
<label>GameId</label>
<input name="games" ng-model="ctrl.game" ng-required="true" ng-maxlength="50" custome-directive-to-check-unique-value >
</md-input-container>

在编辑页面上,它应该是

<md-input-container flex="25">
<label>GameId</label>
<input name="games" ng-model="ctrl.game" ng-required="true" ng-maxlength="50" disabled>
</md-input-container>

对于禁用,我可以使用ng-disabled=ctrl.edit使输入字段禁用方式,为指令custome-directive-to-check-unique-value

p>您可以简单地根据值使用属性ng-showng-hide
<div ng-hide="edit">Edit is False</div>
<div ng-show="edit">Edit is True</div>

如果edit为true,则ng show将为true,显示消息Edit is True

您可以使用两个输入字段,并使用ng-if根据布尔值显示其中一个字段,布尔值指定是添加视图还是编辑视图。

<input ng-if="!ctrl.edit" name="games" ng-model="ctrl.game" ng-required="true" ng-maxlength="50" custome-directive-to-check-unique-value  >
<input ng-if="ctrl.edit" name="games" ng-model="ctrl.game" ng-required="true" ng-maxlength="50" disabled>
  1. 您可以使用ng-disabled指令来禁用或启用您的输入文本,但正如我所看到的,您已经这样做了。

    1. 至于指令禁用,为什么不在指令体中使用if语句,并根据ctrl.edit值检查需要做什么

要做到这一点,只需将输入文本中的ctrl.edit传递给指令,如下所示:

html

<input name="games" ng-model="ctrl.game" ng-required="true" ng-maxlength="50" custome-directive-to-check-unique-value   myFlag = "ctrl.edit">

指令

.directive('customeDirectiveToCheckUniqueValue', function () {
            return {
                restrict: 'AE',
                scope:{
                   myFlag :'='
                 },
                link: function (scope, element, attrs) {
                    //here make your condition and add your code accordingly
                    if(myFlag){
                       //if true your code
                    }else{
                       //if false your code
                     }
                }
            };
        })

希望有帮助,祝你好运。