如何从一个指令内通过双击添加输入的禁用状态的来回切换? [英] How to add toggling of the disabled state of an input via double click from inside a directive?

查看:181
本文介绍了如何从一个指令内通过双击添加输入的禁用状态的来回切换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着以下但输入不被禁用虽然范围的变量正确地更新:

I was trying the following but the input isn't being disabled although the scope variable properly updates:

<body ng-app="myApp">
    <div ng-controller="MyCtrl">
        <input type="text" my-input />
    </div>
</body> 

angular.module('myApp',[])
.controller('MyCtrl', function ($scope) {})
.directive('myInput', ['$compile', function($compile) {
    return {
        scope: true,
        link: function(scope, element, attrs) {
            scope.disabled = false;
            if (!('disabled' in attrs)) {
                element.attr('ng-disabled', 'disabled');                       
            }
            element.bind('dblclick', function() {
                scope.disabled = !scope.disabled;
                alert(scope.disabled);
                scope.$apply();
            });
        }
    };
}]);

请参阅: http://plnkr.co/edit/tpl:rfqcl9AHEoJZEEJxyNn2 p = preVIEW

推荐答案

我已经在你的code一些变化:

I have made some change in your code:

HTML

<input type="text" my-input ng-disabled="disabled" />

JS

angular.module('myApp',[])
.controller('MyCtrl', function ($scope) {})
.directive('myInput', ['$compile', function($compile) {
    return {
        scope: true,
        link: function(scope, element, attrs) {
            scope.disabled = false;
            element.bind('dblclick', function() {
                scope.disabled = !scope.disabled;
                alert(scope.disabled);
                scope.$apply();
            });
        }
    };
}]);

请参阅: http://plnkr.co/edit/g0qtbFJb1V4OxcXNRTVf?p=preVIEW

编辑(添加NG-禁用从内部指令):

HTML

<input type="text" my-input/>

JS

angular.module('myApp',[])
.controller('MyCtrl', function ($scope) {})
.directive('myInput', ['$compile', function($compile) {
    return {
        scope: true,
        link: function(scope, element, attrs) {
            scope.disabled = false;
            element.attr('ng-disabled', 'disabled'); 
            element.removeAttr('my-input'); 
            $compile(element)(scope);
            element.bind('dblclick', function() {
                scope.disabled = !scope.disabled;
                scope.$apply();
            });
        }
    };
}]);

请参阅: http://plnkr.co/edit/g0qtbFJb1V4OxcXNRTVf?p=preVIEW

这篇关于如何从一个指令内通过双击添加输入的禁用状态的来回切换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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