如何使用属性禁用日期字段?

时间:2016-05-14 05:46:43

标签: javascript angularjs angularjs-directive angularjs-scope

我正在尝试使用属性禁用我的字段。我不想使用指令范围属性(=,@,&)我想使用attribute属性来禁用我的 type ='date' field

这是我的代码

http://plnkr.co/edit/eJDRocLYkr8Krh84vFKY?p=preview

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

    app.controller('MainCtrl', function($scope) {
      $scope.name = 'World';
      $scope.clickb=function(){
        alert('dd')
        $scope.disabletest=true;
      }
    });

    app.directive('test',function(){
      return {
        restrict :'E',
        scope:{},
        template:'<input type="date" ng-disable="disabletest">',
        link:function(s,e,a){

        }

      }
    })

我在指令中发送disable属性值,以便在按钮点击时禁用字段。      

我想在按钮点击时使用属性属性

禁用输入字段(type ='date')

3 个答案:

答案 0 :(得分:1)

尝试此操作,将ng-disable更改为ng-disabled,然后创建范围变量

var jimApp = angular.module("mainApp",  []);

jimApp.controller('mainCtrl', function($scope){
  $scope.disabletest = false;
  $scope.clickb=function(){
    $scope.disabletest=!$scope.disabletest;
  };
});

jimApp.directive('test',function(){
  return {
    restrict :'E',
    template:'<input type="date" ng-disabled="disable">',
    link:function(s,e,a){
      a.$observe('disable', function(value) {
      s.disable = s.$eval(a.disable);
    });
  }
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<div ng-app="mainApp" ng-controller="mainCtrl">
  <button ng-click='clickb()'>btn</button>
  <test disable='{{disabletest}}'></test>
</div>

答案 1 :(得分:0)

应该是

 ng-disabled="expression"

的index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
    <script src="app.js"></script>
  </head>

  <body >
    <div ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    <button ng-click='clickb()'>btn</button>
    <input type="date" ng-disabled='disabletest'>    
    </div>

  </body>

</html>

into指令,你必须指定一个属性来获取disabletest值

答案 2 :(得分:0)

虽然你真的不应该使用$ parent,但改变范围是Jimbrooism建议的最佳解决方案。这是没有修改范围的解决方案。改为:

template:'<input type="date" ng-disabled="$parent.disabletest">',

http://plnkr.co/edit/ZBKv63aroXrao7GO9P2u?p=preview