gpt4 book ai didi

javascript - 如何访问附加了 ng-disabled 的响应元素?

转载 作者:行者123 更新时间:2023-12-03 04:02:05 26 4
gpt4 key购买 nike

是否有一种干净的方法来访问 ng-disabled 属性附加到给定函数内部的元素?

Html 元素:

 <input class="needsDisabling" ng-disabled="isFieldDisabled()" type="text">

Controller 中的isFieldDisabled函数:

如何访问此函数中附加 ng-disabled 属性的元素?

$scope.isFieldDisabled = function () {
// How can I access the element where the ng-disabled prop is attached to in this function ?

// if (element has class "needsDisabling")
// return true;
}

I am looking for another way then passing the element as a parameter in the function.

JSFiddle

最佳答案

ngDisabled旨在与您的模型(#2)配合使用,并且不允许在 Controller 中手动操作 DOM 元素(这在 angularjs 中被认为是不好的做法)。但无论如何你仍然可以创建你的 custom directive并手动操作 disabled 属性 (#1):

angular.module('myApp',[])
.directive('myDisabled', [function () {
var myDisabled = {
restrict: 'A',
scope: false,
link : function(scope, element, attrs, ngModelCtrl){
scope.$watch(function() {
return scope.$eval(attrs.myDisabled).apply(scope, element);
}, function(val) {
element.prop('disabled', val);
});
}
}
return myDisabled;
}])
.controller('MyCtrl', ['$scope', function MyCtrl($scope) {

$scope.isFieldDisabled = function (element) {
return angular.element(element).hasClass('disabled');
}

$scope.inputs = [{}, { disabled: true }, {}];

$scope.isInputDisabled = function (input){
return !!input.disabled;
};

}]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.angularjs.org/1.6.4/angular.js" ></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<h2>#1</h2>
<input class="needsDisabling disabled" my-disabled="isFieldDisabled" type="text"/>
<input class="needsDisabling" my-disabled="isFieldDisabled" type="text"/>
<input class="needsDisabling disabled" my-disabled="isFieldDisabled" type="text"/>
<h2>#2</h2>
<div>
<input type="text" ng-repeat="input in inputs" ng-disabled="isInputDisabled(input)" ng-model="input.value"/>
</div>
</div>
</div>

关于javascript - 如何访问附加了 ng-disabled 的响应元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44678549/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com