Joh*_*ith 54 angularjs angularjs-directive
如何使用指令方法启用/禁用锚标记?
例:
JAVASCRIPT:
angular.module('ngApp', []).controller('ngCtrl',['$scope', function($scope){
$scope.create = function(){
console.log("inside create");
};
$scope.edit = function(){
console.log("inside edit");
};
$scope.delete = function(){
console.log("inside delete");
};
}]).directive('a', function() {
return {
restrict: 'E',
link: function(scope, elem, attrs) {
if(attrs.ngClick || attrs.href === '' || attrs.href === '#'){
elem.on('click', function(e){
e.preventDefault();
if(attrs.ngClick){
scope.$eval(attrs.ngClick);
}
});
}
}
};
});
Run Code Online (Sandbox Code Playgroud)
Was*_*moo 56
更新: 禁用href在链接函数返回中更好.以下代码已更新.
aDisabled之前自然执行,ngClick因为指令按字母顺序排序.当aDisabled被重命名为tagDisabled,该指令也不能正常工作.
要"禁用""a"标记,我需要以下内容:
href 单击时不要遵循的链接ngClick 点击时不发射的事件disabled类来更改样式该指令通过模仿ngDisabled指令来完成此操作.基于a-disabled指令的值,所有上述功能都被切换.
myApp.directive('aDisabled', function() {
return {
compile: function(tElement, tAttrs, transclude) {
//Disable ngClick
tAttrs["ngClick"] = "!("+tAttrs["aDisabled"]+") && ("+tAttrs["ngClick"]+")";
//return a link function
return function (scope, iElement, iAttrs) {
//Toggle "disabled" to class when aDisabled becomes true
scope.$watch(iAttrs["aDisabled"], function(newValue) {
if (newValue !== undefined) {
iElement.toggleClass("disabled", newValue);
}
});
//Disable href on click
iElement.on("click", function(e) {
if (scope.$eval(iAttrs["aDisabled"])) {
e.preventDefault();
}
});
};
}
};
});
Run Code Online (Sandbox Code Playgroud)
这是一个css样式,可能表示已禁用的标记:
a.disabled {
color: #AAAAAA;
cursor: default;
pointer-events: none;
text-decoration: none;
}
Run Code Online (Sandbox Code Playgroud)
z0r*_*z0r 23
我的问题略有不同:我有定义一个锚标签,href我想ng-disabled用来防止链接在点击时去任何地方.解决方案是取消href禁用链接的时间,如下所示:
<a ng-href="{{isDisabled ? '' : '#/foo'}}"
ng-disabled="isDisabled">Foo</a>
Run Code Online (Sandbox Code Playgroud)
在这种情况下,ng-disabled仅用于样式化元素.
如果您想避免使用非官方属性,则需要自己设置样式:
<style>
a.disabled {
color: #888;
}
</style>
<a ng-href="{{isDisabled ? '' : '#/foo'}}"
ng-class="{disabled: isDisabled}">Foo</a>
Run Code Online (Sandbox Code Playgroud)
对于不想要复杂答案的人,我使用Ng-If来解决类似问题:
<div style="text-align: center;">
<a ng-if="ctrl.something != null" href="#" ng-click="ctrl.anchorClicked();">I'm An Anchor</a>
<span ng-if="ctrl.something == null">I'm just text</span>
</div>
Run Code Online (Sandbox Code Playgroud)
修改@ Nitin对动态禁用的回答:
angular.module('myApp').directive('a', function() {
return {
restrict: 'E',
link: function(scope, elem, attrs) {
elem.on('click', function(e) {
if (attrs.disabled) {
e.preventDefault(); // prevent link click
}
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
这会在每次单击时检查disabled属性及其值的存在.
我希望锚标记能够指向带有 url 的静态页面。我认为按钮更适合您的用例,然后您可以使用 ngDisabled 来禁用它。来自文档: https: //docs.angularjs.org/api/ng/directive/ngDisabled
| 归档时间: |
|
| 查看次数: |
122272 次 |
| 最近记录: |