word count limit in Angularjs(front page in bootstrap) - angularjs

i want to apply word count in angular js (eg in Text Box " I am Good " word count should be 3 ) and i also want to limit the word count
please help
thanks in advance

I make a Working Plunker which counts words splitted by blank space.
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;
}
});
You can use this count to limit whatever you want. For instance, lets suppose you want to show "Hello There" only if ng-model has more than 3 words:
<div ng-show="wordCount>3">Hello There</div>
If you need to watch for how many words are contained in an input box, you simply attach a $watch task or use ng-change on that field, everytime it changes, you check how many words are in there, then you can deny more words to get written.
I hope I've been helpful.

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
};

Related

Implementing rich text feature in Angularjs with angular-smiles.min.js

I am new to AngularJS and I am working on implementing rich texts for comments, bold, italic etc. I came across angular-smiles which is quiet easy and amazing to use.
<body ng-controller="SomeCtrl">
<p ng-bind-html="message | smilies "></p>
<div class="input-group">
<span class="input-group-addon"
smilies-selector="message"
smilies-placement="right"
smilies-title="Smilies"></span>
<textarea ng-model="message" focus-on-change="message" class="form-control"></textarea>
</div>
I also have to implement other features like ** to bold and keeping line breaks as <br> . Can someone please guide me on the angular way of doing it. A small hint with relevant topic is good enough to help me out as the project in hand has very limited time to complete.
Your best bet will be filters. I would highly recommend you to go through it.
now, just to help you out, I have written down a small code to help you grab it better.
app.controller('MainCtrl', function($scope,FILTER_FUNCTIONS) {
$scope.message = '';
// remove this,just to show you line breaks
$scope.$watch('message',function(newVal,oldVal){
console.log(newVal)
})
});
function f1(str){
var obj = { expr: /\n+?/g, value: '<br>' };
return str.replace(obj.expr, obj.value)
};
function f2(str){
var boldArray = str.split("**");
console.log(boldArray)
if(boldArray.length < 3){
return str;
}else{
for(var count = 0 ; count < boldArray.length ; count++){
if(count%2 !== 0 && (count+1 !== boldArray.length)){
boldArray[count] = '<strong>'+boldArray[count]+'</strong>'
}else if(count%2 !== 0){
boldArray[count] = '**'+boldArray[count]
}
}
return boldArray.join("");
}
}
var arr = [f1,f2];
app.value('FILTER_FUNCTIONS',arr);
app.filter('richText', function(FILTER_FUNCTIONS) {
return function(string) {
return FILTER_FUNCTIONS.reduce(function(result, someFn) {
return someFn(result);
}, string || '');
};
});
and in your html , add message | smilies | richText.
you can increase the rich text feature just by adding new functions in your array arr

How to give default or initial selection for md-checkbox where its data comes from JSON

I have a list of <md-checkbox> where it is repeated using JSON array.
I want to give an initial selection for 2 checkboxes. Please help me on this.
My js code:
$scope.elecselected = [];
$scope.toggle = function (elecitem, eleclist) {
var idx = eleclist.indexOf(elecitem);
if (idx > -1) {
eleclist.splice(idx, 1);
}
else {
eleclist.push(elecitem);
}
console.log("item:"+elecitem+ " List:"+ eleclist);
};
$scope.exists = function (elecitem, eleclist) {
return eleclist.indexOf(elecitem) > -1;
};
$scope.electrical = [{"ID":"161","Value":"ABC","Name":"AAAA BBB CCC","IsDefault":"FALSE"},{"ID":"162","Value":"CDE","Name":"CCC DDD EEE","IsDefault":"Y"},{"ID":"163","Value":"EFG","Name":"EEE FFF GGG","IsDefault":"FALSE"}];
HTML Code:
<div layout="row" style="margin-left: 5px;font-size: x-small;" ng-repeat="attribute in electrical">
<md-checkbox ng-checked="exists(attribute.ID, elecselected)" ng-click="toggle(attribute.ID, elecselected)">
<label name="{{value.ID}}">{{attribute.Name}}</label>
</md-checkbox>
</div>
I had tested with normal array values as $scope.elecitems = [1,2,3,4,5];
$scope.elecselected = [2,4]; and this worked but while giving JSON array it is not working. Please help...
Thanks #DincaAdrian for the idea of giving attribute.IsDefault === "Y" in ng-checked. Also I had added codes to maintain the selection procedure.
Now its working fine. Some logic must be added on top of this code to get the selected values.

Filter on string

I'm learning angularjs and got an exercise that wants me to Use angular filter to show a title in the following format :
first letter of each word upper cased and each other letter lower cased also
remove any non-English letters from the title. For example:
A title with the name
“##THIS is a Title!!”
should be changed to
“This Is A Title”
I'm getting each title from an array of objects and present them like so.
<div ng-repeat="obj in objects">
<h3 class="panel-title">{{obj.Title}}</h3>
</div>
i understand that filter receives an array and filters through it . but this requires me to filter the string.
been searching for a while, how can i do this?
please refer below fiddle
http://jsfiddle.net/HB7LU/28315/
<div ng-controller="MyCtrl">
Hello, {{ name | ordinal|capitalize }}
</div>
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.name = 'Super hero!!12##3';
}
myApp.filter('ordinal', function() {
// Create the return function
// set the required parameter name to **number**
return function(strTitle) {
// Ensure that the passed in data is a number
// If the data is not a number or is less than one (thus not having a cardinal value) return it unmodified.
strTitle=strTitle.replace(/[^a-zA-Z ]/g, "")
return strTitle;
}
});
myApp.filter('capitalize', function() {
return function(input){
if(input.indexOf(' ') !== -1){
var inputPieces,
i;
input = input.toLowerCase();
inputPieces = input.split(' ');
for(i = 0; i < inputPieces.length; i++){
inputPieces[i] = capitalizeString(inputPieces[i]);
}
return inputPieces.toString().replace(/,/g, ' ');
}
else {
input = input.toLowerCase();
return capitalizeString(input);
}
function capitalizeString(inputString){
return inputString.substring(0,1).toUpperCase() + inputString.substring(1);
}
};
});
angular.module('app', []).filter('myFilter', function(){
return function(input){
if(!input)
return;
var out = '';
var english = /^[A-Za-z0-9 ]*$/;
for(var letter of input)
if(english.test(letter))
out += letter;
var result = '';
for(var i = 0; i < out.length; i++)
result += out[i][(i === 0 || out[i-1] == ' ') ? 'toUpperCase' : 'toLowerCase']();
return result;
}
})
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<body ng-app="app">
<input ng-init='text="##THIS is a Title!!"' type='text' ng-model='text'>
<p>{{text | myFilter}}</p>
</body>

rendering html from a controller in angular

Hopefully someone can point my in the right direction.
I am building a web app and part of it requires a user to click a button as fast as they can to obtain a score. The design dictates that I will need to show this score in double digits i.e 9 would be 09 so for styling I need to wrap span tags around each digit.
I have got everything working as required, I'm just having an issue with outputting the score that is wrapped in span tags as rendered html in my view.
I've put together a fiddle for the section that is causing me problems. Any advice, help, best practices etc is much appreciated.
What I've tried:
I've included a few of the things I've tried. Basically they involve using $sce and trying to ng-bind-html in the view. Attempt 3 seems the most logical to me but the $scope.count isn't being updated. I'm guessing I need to add a $watch or $apply function to keep it binded? but I'm not too sure how to implement it or even if this is good practice. Also, because I'm outputting html is it better practice to do this in a directive?
Fiddle http://jsfiddle.net/funkycamel/gvxpnvqp/4/
HTML
<section ng-app="myApp">
<div ng-controller="MyController">
<button ng-click="add(1)">add</button>
<!-- First attempt -->
<p class="first-attempt">{{ pad(count) }}</p>
<!-- Second attempt -->
<!-- in order for this attempt to work I have to call the pad2 function which
returns trustedHtml -->
{{ pad2(count) }}
<p class="second-attempt" ng-bind-html="trustedHtml"></p>
<!-- Third attempt -->
<p class="third-attempt" ng-bind-html="moreTrustedHtml"></p>
</div>
Javascript
var app = angular.module('myApp', []);
app.controller('MyController', ['$scope', '$sce', function ($scope, $sce) {
// Set initial count to 0
$scope.count = 0;
// function to add to $scope.count
$scope.add = function (amount) {
$scope.count += amount;
};
// Attempt 1
// make sure number displays as a double digit if
// under 10. convert to string to add span tags
$scope.pad = function (number) {
var input = (number < 10 ? '0' : '') + number;
var n = input.toString();
var j = n.split('');
var newText = '';
var trustedHtml = '';
for (var i = 0; i < n.length; i++) {
newText += '<span>' + n[i] + '</span>';
}
return newText;
};
// Attempt 2 - trying to sanitise output
// same as above just returning trusted html
$scope.pad2 = function (number) {
var input = (number < 10 ? '0' : '') + number;
var n = input.toString();
var j = n.split('');
var newText = '';
var trustedHtml = '';
for (var i = 0; i < n.length; i++) {
newText += '<span>' + n[i] + '</span>';
}
// return sanitised text, hopefully
$scope.trustedHtml = $sce.trustAsHtml(newText);
return $scope.trustedHtml;
};
// Attempt 3
// Trying to sanitise the count variable
$scope.moreTrustedHtml = $sce.trustAsHtml($scope.pad($scope.count));
}]);
These currently output
<span>0</span><span>0</span>
<span>0</span><span>0</span>
00
00
Again any advice/help is greatly appreciated.
Far simpler solution:
HTML
<p>{{ count < 10 ? '0' + count : count}}</p>
Controller:
app.controller('MyController', ['$scope', function ($scope) {
$scope.count = 0;
$scope.add = function (amount) {
$scope.count += amount;
};
}]);
DEMO
If you prefer you can do the padding in the controller instead, just use another variable
app.controller('MyController', ['$scope', function ($scope) {
var count = 0;
$scope.countText = '0';
$scope.add = function (amount) {
count += amount;
$scope.countText = count < 10 ? '0' + count : count;
};
}]);

Get/Set values of dynamical generated input fields using ng-repeat in Angular

I have an input field which once filled with a number populates that count of additional input fields. I can't figure out how to get the values inserted in those generated input fields. Any help is appreciated, and oh, I did try various things and even with angular.element, or solely with jquery, but failed, so any explanation on how to do this is welcome.
Here is my jsfiddle, and the code c/p-ed here:
<div ng-controller="MyCtrl">
<input type="text" ng-model="cntInputs" placeholder="#Inputs"><br/>
<input ng-repeat="i in getTimes()" type="text" placeholder="{{i}}" id="input_{{i}}">
<ul>
<li ng-repeat="j in getTimes()">
Inputed value is: {{getValue(j)}}
</li>
</ul>
</div>
js:
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.cntInputs = 0;
$scope.getTimes=function(){
var a = new Array();
for(var i=1; i <= $scope.cntInputs; i++)
a.push(i);
return a;
};
$scope.getValue = function(id){
//here get the value of that inserted in the element with the id of "input_" + id
return angular.element("input_" + id);
}
}
So add ng-model="inputs[i-1]" to your text field
Then in your controller add $scope.inputs= [];
Then in your getValue function: return $scope.inputs[id-1];
If you make your getTimes function 0 based you wouldn't need the -1s
Updated your fiddle: http://jsfiddle.net/7MhLd/60/

Resources