使用 ng-click 传递对 DOM 对象的引用 [英] Pass a reference to DOM object with ng-click

查看:22
本文介绍了使用 ng-click 传递对 DOM 对象的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个元素在 ng-click 上具有相同的回调:

<button ng-click="doSomething()"></button><button ng-click="doSomething()"></button><button ng-click="doSomething()"></button><button ng-click="doSomething()"></button>

//在控制器中:$scope.doSomething = function() {//如何获得对触发函数的按钮的引用?};

如何获得对调用 doSomething 的对象的引用?(我需要从中删除一个 attr)

解决方案

angular 方式见angular docs :)

https://docs.angularjs.org/api/ng/directive/ngReadonly>

这是他们使用的示例:

检查我是否将文本设为只读:<input type="checkbox" ng-model="checked"><br/><input type="text" ng-readonly="checked" value="I'm Angular"/>

基本上,角度方法是创建一个模型对象,该对象将保存输入是否应为只读,然后相应地设置该模型对象.angular 的美妙之处在于大多数时候你不需要做任何 dom 操作.您只需按照模型设置的方式进行 Angular 渲染(让 Angular 为您执行 dom 操作并保持代码清洁).

所以基本上在您的情况下,您可能想要执行以下操作或查看这个工作示例.

<button ng-click="isInput1ReadOnly = !isInput1ReadOnly">点击我</button><input type="text" ng-readonly="isInput1ReadOnly" value="Angular Rules!"/>

I have multiple elements with the same callback on ng-click:

<button ng-click="doSomething()"></button>
<button ng-click="doSomething()"></button>
<button ng-click="doSomething()"></button>
<button ng-click="doSomething()"></button>

// In controller:
$scope.doSomething = function() {
  // How do I get a reference to the button that triggered the function?
};

How can I get the reference to the object which made the call to doSomething? (I need to remove an attr from it)

解决方案

The angular way is shown in the angular docs :)

https://docs.angularjs.org/api/ng/directive/ngReadonly

Here is the example they use:

<body>
    Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
    <input type="text" ng-readonly="checked" value="I'm Angular"/>
</body>

Basically the angular way is to create a model object that will hold whether or not the input should be readonly and then set that model object accordingly. The beauty of angular is that most of the time you don't need to do any dom manipulation. You just have angular render the view they way your model is set (let angular do the dom manipulation for you and keep your code clean).

So basically in your case you would want to do something like below or check out this working example.

<button ng-click="isInput1ReadOnly = !isInput1ReadOnly">Click Me</button>
<input type="text" ng-readonly="isInput1ReadOnly" value="Angular Rules!"/>

这篇关于使用 ng-click 传递对 DOM 对象的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆