【问题标题】:how to check textbox isEmpty in angularJs Factory?如何在angularJs Factory中检查文本框isEmpty?
【发布时间】:2015-12-08 05:03:24
【问题描述】:

如何在 angularjs Factory 中检查文本框 isEmpty?

我的 HTML 源代码是

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl"> 
    <input type="text" ng-model="test">
</div>
</body>
</html>

【问题讨论】:

  • test === null 或 test===undefined 或 typeof test === "undefined"
  • 请以完整脚本提供您的解决方案。如何编写 angularJS 工厂以及如何访问 TextBox 中的工厂?

标签: html angularjs angularjs-factory angularjs-ng-model


【解决方案1】:

angular.module('myApp', [])
  .controller('customersCtrl', function($scope){
    $scope.changed = function(){
      if(!$scope.test){
        $scope.msg = 'empty';
      } else {
        $scope.msg = 'not empty';
      }
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


<div ng-app="myApp" ng-controller="customersCtrl"> 
   <input type="text" ng-model="test" ng-change="changed()"/>
    {{ test }} | {{ msg }}
 </div>

【讨论】:

  • 我需要一个 angularJS 工厂方法来验证 TextBox isEmpty。
  • 然后自己创造。
【解决方案2】:
var customersCtrl = function($scope,Validate){

    var isEmpty = Validate.isEmpty($scope.test);

    $scope.Validation = Validate;
    if(isEmpty){
        console.info('Textbox is empty');
    }else{
        console.info('Textbox is not empty');
    }
};


angular.module('myApp').controller('customersCtrl', customersCtrl);

var Validate = function() {

    var factory = {};

    factory.isEmpty = function(val){
        var result = false;
        if(!val){
            result =  true;
        }

        return result;
    };


    return factory;


};



angular.module('myApp').factory('Validate', Validate);

这里是Plunker,根据您的要求。

【讨论】:

  • 如何将此验证工厂与 TextBox 的 OnChange 事件绑定?
  • @B.Balamanigandan - 看看更新后的答案。希望这会有所帮助。
【解决方案3】:

在您的控制器中,您可以随时检查模型值。喜欢

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

app.controller('customersCtrl', function($scope) {

  if($scope.test == ""){
   // textbox is empty, do your stuff here
  }

});

【讨论】:

  • 我需要一个 angularJS 工厂方法来验证 TextBox isEmpty。
【解决方案4】:

附加技巧!

你可以在 angular expression 上查看。请参阅下面的示例!

var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope) {
    $scope.test = "";
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl"> 
    <input type="text" ng-model="test">
    <span ng-show="test.length == 0">
  is empty </span>
</div>

</body>
</html>

希望!

【讨论】:

  • 我需要一个 angularJS 工厂方法来验证 TextBox isEmpty。
  • 不,不是这样。请访问我在此处粘贴的 URL,它包含我需要的工厂方法。 jsfiddle.net/agrublev/QjVq3
猜你喜欢
  • 2016-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-12
  • 1970-01-01
相关资源
最近更新 更多