如何向指令添加布尔属性?

3
在HTML中,存在像selected这样的属性:
<option selected>This option is selected</option>

这个属性要么存在,要么不存在,可以翻译为开或关(布尔值)。

我找不到一种方法来为AngularJs指令创建这样的属性。有没有办法?

一个例子:

<modal ng-show="modal.show" with-backdrop> // "with-backdrop" is a boolean attribute.

你尝试过什么?你可以在“attrs”对象中测试属性的存在。 - JoseM
2个回答

0

我再次阅读了你的问题,发现我错了。要实现你想要的效果,你应该这样做:

HTML元素: <modal id="myModal" ng-show="modal.show" with-backdrop>

然后在你的控制器中:

function somethingController() {
  var modalElement = document.querySelector('#myModal');

  // If you want to check that element have your attribute.
  var isMyAttributeSet = modalElement.getAttribute('with-backdrop') !== null;

  // If you want to set up the attribute.
  modalElement.setAttribute('with-backdrop', '');

}

setAttribute 方法需要两个参数(属性名称,属性值),但如果您将空字符串作为第二个参数传递,则该属性将被视为您想要的方式。我已在 Chrome 控制台中进行了测试 :)


-1

这取决于你要做什么。在你的例子中,你想知道哪个选项被选中了。这可以通过检查


1
非常抱歉,如果我的问题不够清晰,但我并不是在问如何检查表单元素是否被选中。我想知道如何为AngularJS指令创建布尔属性,使其像正常的HTML布尔属性一样运作。 - sinθ

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