【问题标题】:Angular - ng-click on a div works only when you click on specific areas of a divAngular - 仅当您单击 div 的特定区域时,对 div 的 ng-click 才有效
【发布时间】:2014-08-19 21:28:46
【问题描述】:

我正在尝试创建一个包含一堆禁用字段的 div。单击 div 中的任意位置即可启用它们。

我发现单击 div 中的任意位置会触发 ng-click,而单击禁用的下拉菜单似乎不会触发 ng-click。这是一个例子。

http://jsfiddle.net/sJZf7/9/

Javascript:

var app = angular.module('App', []);
function ctrl($scope) {
    $scope.disabled = true;
    $scope.enable = function () {
        $scope.disabled = false;
    }
}

发生了什么事?

【问题讨论】:

  • Event on a disabled input的可能重复
  • 我认为你不能在禁用的元素上触发鼠标事件。
  • 您不能在禁用元素上触发事件。一种可能的解决方法:更改该事件的默认操作并更改元素的样式,使其看起来像已禁用。
  • @Mritunjay - 如果是这样,为什么它对文本输入起作用?此外,事件监听器在 div 上,而不是在 select 上。

标签: javascript angularjs angularjs-ng-click


【解决方案1】:

您不能在禁用的元素上触发事件。我会使用 CSS :after 伪元素来创建一个禁用的覆盖,可以点击:

<div ng-click="enable()" ng-class="{'disabled': disabled, 'enabled': !disabled}">
    <select ng-disabled="disabled">
        <option>Disabled DropDown</option>
    </select>
    <input type="text" ng-disabled="disabled" size="100" placeholder="Click here to enable the dropdown" />
</div> 

.disabled {
    position: relative;
}
.disabled:after {
    position: absolute;
    content:'';
    width: 100%;
    height: 100%;
    opacity: .3;
    background: yellow;
    top: 0;
    left: 0;
}

在这里提琴:http://jsfiddle.net/sJZf7/11/

【讨论】:

  • 实际上,您不需要“启用”类。
    就足够了。
【解决方案2】:

你可以找到一个 jsfiddle 来解决你的问题here

html

<h2>
    The dropdown gets enabled if I click anywhere other than the disabled dropdown
</h2>
<div ng-app="App" ng-controller="ctrl" style="border: 10px solid black;">
     <div>
        <select ng-disabled="disabled">
            <option>Disabled DropDown</option>
        </select>
        <input type="text" ng-click="enable();" size="100" placeholder="Click here to enable the dropdown" />
        <select>
            <option>Enabled dropdown</option>
        </select>
    </div>
</div>

javascript

var app = angular.module('App', []);

function ctrl($scope) {
    $scope.disabled = true;
    $scope.enable = function (disabled) {
        $scope.disabled = false;
    }
}

【讨论】:

    【解决方案3】:

    之所以这样工作,是因为您为其分配 enable 函数的盒子模型是整个 div

    我已经以最小的影响改变了你的小提琴以使其正常工作

    http://jsfiddle.net/sJZf7/10/

    <select ng-disabled="disabled">
      <option>Disabled DropDown</option>
    </select>
    <label ng-click="enable()"><input type="text" ng-disabled="disabled" size="100" placeholder="Click here to enable the dropdown" /></label>
    <select>
      <option>Enabled dropdown</option>
    </select>
    

    【讨论】:

    • 我相信发帖者希望在单击 div 中的任何位置(包括选择)时触发 ng-click。
    • 我认为你是对的,我应该在 stackoverflow 之前喝咖啡;)
    • 咖啡是一种强大的工具
    猜你喜欢
    • 1970-01-01
    • 2017-10-24
    • 1970-01-01
    • 2016-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    相关资源
    最近更新 更多