Angularjs中的字数限制(引导程序中的首页)

时间:2016-07-01 11:33:16

标签: angularjs

我想在角度js中应用字数(例如在文本框中“我很好”字数应该是3)并且我还想限制字数 请帮忙

提前致谢

2 个答案:

答案 0 :(得分:0)

我制作一个Working Plunker来计算由空格分割的单词。

<强> HTML

<body ng-controller="myCtrl">
   Write in here!
   <input type="text" ng-model="myModel"/>
     <button ng-click="countWords(myModel)">Click Me</button>
   <h1 ng-show="wordCount">You have {{wordCount}} words!</h1>
</body>

<强> JS

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

myApp.controller("myCtrl", function($scope){

  $scope.split = [];
  $scope.wordCount = 0;

  $scope.countWords = function(text){

    /*Split by Space*/
    $scope.split = text.split(/(\s+)/);

    /*Remove all the blank spaces*/
    for(var i=0; i<=$scope.split.length; i++){
      if($scope.split[i] === " "){
        $scope.split.splice(i, 1);
      }
    }

    /*Count Words*/
    $scope.wordCount = $scope.split.length;

  }
});

您可以使用此计数来限制您想要的任何内容。例如,假设您想要显示&#34; Hello There&#34;仅当ng-model超过3个字时才会出现:

<div ng-show="wordCount>3">Hello There</div>

如果您需要关注输入框中包含的单词数量,您只需附加$watch任务或在该字段上使用ng-change,每次更改时,都会检查有多少单词在那里,你可以拒绝更多的话来写。

我希望我能提供帮助。

答案 1 :(得分:0)

enter code here$scope.countOf = function(text,count) {
        var s = text ? text.split(/\s+/) : 0; // it splits the text on space/tab/enter
          console.log(s.length);
           $scope.wc=s.length;
          if(s.length === count + 1){


          //  alert('limit exceded');
        //  text.substr(0,text.length);
          }
          return s ? s.length : '';
enter code here

      };