Select at least one checkbox in AngularJS from each table - angularjs
I have to validate a questionnaire before submitting it. The question-answer tables are generated dynamically from a JSON file. Before submitting the questionnaire, at least one answer should be checked from each question. For an unattempted question, it should validate as 'Please select at least one checkbox/answer'.
My problem: I am able to validate at least once checkbox selection for one question, but I not able to validate for all questions. It validates if any one of the checkbox is selected on whole page. I want each question should have at least one answer selected.
My code shows validation error [Please select at least one checkbox/answer'] even for the selected answer question. It should show validation error only on the questions which are not attempted [i.e. questions whose at least one answer is also not selected].
I have gone through multiple posts on AngularJS group check box validation, but I wasn't able to satisfy my problem.
Can anyone please help me out?
Thanks in advance!
quest_answer.json
[
{
"id": "0",
"header": "Fruits",
"question": "Which fruit do you like?",
"answer": [
{"aid": 0, "value" : "Apple", "isChecked" : false},
{"aid": 1, "value" : "Banana", "isChecked" : false},
{"aid": 2, "value" : "Strawberry", "isChecked" : false},
{"aid": 3, "value" : "Grapes", "isChecked" : false},
{"aid": 4, "value" : "Mango", "isChecked" : false}
],
"notes":""
},
{
"id": "1",
"header": "Vegetables",
"question": "Which vegetable do you like?",
"answer": [
{"aid": 0, "value" : "Potato", "isChecked" : false},
{"aid": 1, "value" : "Spinach", "isChecked" : false},
{"aid": 2, "value" : "Cabbage", "isChecked" : false},
{"aid": 3, "value" : "Brinjal", "isChecked" : false}
],
"notes":""
},
{
"id": "2",
"header": "Color",
"question": "Which color do you like?",
"answer": [
{"aid": 0, "value" : "Red", "isChecked" : false},
{"aid": 1, "value" : "Orange", "isChecked" : false},
{"aid": 2, "value" : "Green", "isChecked" : false},
{"aid": 3, "value" : "Blue", "isChecked" : false},
{"aid": 4, "value" : "Pink", "isChecked" : false}
],
"notes":""
},
{
"id": "3",
"header": "Animal",
"question": "Which animal do you like?",
"answer": [
{"aid": 0, "value" : "Monkey", "isChecked" : false},
{"aid": 1, "value" : "Dog", "isChecked" : false},
{"aid": 2, "value" : "Cat", "isChecked" : false},
{"aid": 3, "value" : "Cow", "isChecked" : false}
],
"notes":""
}
]
questionnaire.html
<div ng-init="init()">
<div class="module">
<div class="module-head">
<center><h3> <b>Evaluation</b> </h3></center>
</div>
<center>
<div class="module-body" >
<div> Questionnaire About the Project/Initiative</div>
<hr>
<form name="qForm" ng-submit="evaluate_Report(qForm.$valid)" novalidate>
<hr>
<div>Question Set</div>
<hr>
<div ng-repeat="myQuestion in questionnaire">
<table id="personal_table" class="table table-striped table-bordered table-hover" style="width:70%">
<tbody>
<hr>
<center><thead>{{myQuestion.header}}</thead></center>
<tr style="width:100%">
<th rowspan="{{questionnaire[$index].answer.length+1}}" scope="rowgroup"style="width:50%">
{{myQuestion.question}}</th>
<th style="width:2%">:</th>
<th style="width:48%">Tick all that apply
<div ng-show="qForm.$submitted && qForm.ansCheck.$error.required">
Please select atleast one checkbox</div>
</th>
</tr>
<tr ng-repeat="answer in questionnaire[$index].answer">
<td><input type="checkbox" name="ansCheck" ng-model="answer.isChecked" ng-change="selectAnswer($parent.$index, $index, answer)" ng-required="!anySelected($parent.$index,answer)" >
</td>
<td> {{answer.value}} </td>
</tr>
<tr style="width:100%">
<td style="width:50%" id="q2">Special Notes</td>
<td style="width:1%">:</td>
<td style="width:49%"><input type=text ng-model="personal_info_notes">
{{myQuestion.notes}} </td>
</tr>
</tbody>
</table>
</div>
<center>
<button type=submit id="btn_evaluate">Evaluate Report</button>
</center>
<hr>
<hr>
</div>
</div>
</div>
questionnaire.js
app.controller('questionnaire', ['$scope','$http','$sce','$routeParams',function($scope,
$http, $sce, $routeParams) {
$scope.questionAttempted = []; // an array containing question ids which are attempted
$scope.questionAnswerAttempted=[];//an array containing answers which are checked
$scope.init=function()
{
$http.get('quest_answer.json').then(function(questionnaireData){
$scope.questionnaire = questionnaireData.data;
});
}
$scope.selectAnswer = function(qIndex, aIndex, selectedAnswer)
{
var selectedIndex = $scope.questionAnswerAttempted.indexOf(selectedAnswer.value);
var selectedQuestion= $scope.questionAttempted.indexOf(qIndex);
if(selectedIndex == -1 && selectedAnswer.isChecked){
$scope.questionAnswerAttempted.push(selectedAnswer.value);
if(selectedQuestion == -1){
$scope.questionAttempted.push(qIndex);
}
}else if(!selectedAnswer.isChecked && selectedIndex != -1){
$scope.questionAnswerAttempted.splice(selectedIndex,1);
var aLength = $scope.questionnaire[qIndex].answer.length;
//Remove the question id from the questionAttempted array only if none of the answers are checked.
if(aLength >0){
for(a=0;a<aLength;a++){
if($scope.questionnaire[qIndex].answer[a].isChecked){
console.log("Atleast one answer is checked for this question.
So no of questions attempted remains same:" + $scope.questionAttempted.length);
flag = false;
break;
}else{
flag = true;
}
}
if(flag){
$scope.questionAttempted.splice(selectedQuestion,1);
console.log("No answers are checked for this question. So removing it");
console.log("No of questions attempted after splicing:" + $scope.questionAttempted.length);
}
}
}
}
// For ng-required attribute of checkboxes. Should return 'true' for attempted question and 'false' for unattempted question
$scope.anySelected = function(qIndex,answer){
var qaLength =$scope.questionAttempted.length;
if(qaLength > 0){
for(var q = 0; q < qaLength ; q++){
if($scope.questionAttempted[q] == qIndex ){
return true;
}else{
return false;
}
}
}else{
return false;
}
}
$scope.evaluate_Report = function(isValid)
{
if(isValid){
alert('Form is valid');
}else{
alert('Form is Incomplete');
}
}
}]);
app.controller('questionnaire', ['$scope','$http','$sce','$routeParams',function($scope, $http, $sce, $routeParams) {
$scope.questionAttempted = []; // an array containing question ids which are attempted
$scope.questionAnswerAttempted=[];//an array containing answers which are checked
$scope.init=function()
{
$http.get('quest_answer.json').then(function(questionnaireData){
$scope.questionnaire = questionnaireData.data;
});
}
$scope.selectAnswer = function(qIndex, aIndex, selectedAnswer)
{
var selectedIndex = $scope.questionAnswerAttempted.indexOf(selectedAnswer.value);
var selectedQuestion= $scope.questionAttempted.indexOf(qIndex);
if(selectedIndex == -1 && selectedAnswer.isChecked){
$scope.questionAnswerAttempted.push(selectedAnswer.value);
if(selectedQuestion == -1){
$scope.questionAttempted.push(qIndex);
}
}else if(!selectedAnswer.isChecked && selectedIndex != -1){
$scope.questionAnswerAttempted.splice(selectedIndex,1);
var aLength = $scope.questionnaire[qIndex].answer.length;
//Remove the question id from the questionAttempted array only if none of the answers are checked.
if(aLength >0){
for(a=0;a<aLength;a++){
if($scope.questionnaire[qIndex].answer[a].isChecked){
console.log("Atleast one answer is checked for this question. So no of questions attempted remains same:" + $scope.questionAttempted.length);
flag = false;
break;
}else{
flag = true;
}
}
if(flag){
$scope.questionAttempted.splice(selectedQuestion,1);
console.log("No answers are checked for this question. So removing it");
console.log("No of questions attempted after splicing:" + $scope.questionAttempted.length);
}
}
}
}
// For ng-required attribute of checkboxes. Should return 'true' for attempted question and 'false' for unattempted question
$scope.anySelected = function(qIndex,answer){
var qaLength =$scope.questionAttempted.length;
if(qaLength > 0){
for(var q = 0; q < qaLength ; q++){
if($scope.questionAttempted[q] == qIndex ){
return true;
}else{
return false;
}
}
}else{
return false;
}
}
$scope.evaluate_Report = function(isValid)
{
if(isValid){
alert('Form is valid');
}else{
alert('Form is Incomplete');
}
}
}]);
.module {
/* box-shadow: 0 0 3px rgba(0,0,0,.1); */
border-color: #e9e9e9;
margin-bottom: 50px;
background-color: #fff;
/* border-radius: 4px;*/
/* -webkit-box-shadow: 0 1px 1px rgba(0,0,0,.05);*/
box-shadow: 0 1px 1px rgba(0,0,0,.05);
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
border: 1px solid #ccc;
border-bottom-color: #bbb;
-webkit-box-shadow: 0 0 1px rgba(0,0,0,0.2);
-moz-box-shadow: 0 0 1px rgba(0,0,0,0.2);
box-shadow: 0 0 1px rgba(0,0,0,0.2);
}
.module-head {
color: #767676;
background-color: #f6f6f6;
border-color: #e9e9e9;
padding: 10px 15px;
border-bottom: 1px solid transparent;
border-top-right-radius: 3px;
border-top-left-radius: 3px;
}
.module-head h3 {
font-size: 20px;
line-height: 20px;
height: 20px;
margin: 0;
font-weight: bold;
}
.module-body {
padding: 15px;
width:1350px;
margin-right: auto;
margin-left: auto;
}
<!DOCTYPE html>
<html lang="en">
<head>
<!-- title and meta -->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv='REFRESH' content='43200'/>
<meta name="Pragma" content="no-cache;">
<title>Web</title>
<link type="text/css" rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<link type="text/css" rel="stylesheet" href="css/theme.css">
</head>
<body ng-app="app">
<div ng-init="init()">
<div class="module">
<div class="module-head">
<center><h3> <b>Evaluation</b> </h3></center>
</div>
<center>
<div class="module-body" >
<div> Questionnaire About the Project/Initiative</div>
<hr>
<form name="qForm" ng-submit="evaluate_Report(qForm.$valid)" novalidate>
<hr>
<div>Question Set</div>
<hr>
<div ng-repeat="myQuestion in questionnaire">
<table id="personal_table" class="table table-striped table-bordered table-hover" style="width:70%">
<tbody>
<hr>
<center><thead>{{myQuestion.header}}</thead></center>
<tr style="width:100%">
<th rowspan="{{questionnaire[$index].answer.length+1}}" scope="rowgroup"style="width:50%">{{myQuestion.question}}</th>
<th style="width:2%">:</th>
<th style="width:48%">Tick all that apply <div ng-show="qForm.$submitted && qForm.ansCheck.$error.required">Please select atleast one checkbox</div> </th>
</tr>
<tr ng-repeat="answer in questionnaire[$index].answer">
<td><input type="checkbox" name="ansCheck" ng-model="answer.isChecked" ng-change="selectAnswer($parent.$index, $index, answer)" ng-required="!anySelected($parent.$index,answer)" >
</td><td> {{answer.value}} </td>
</tr>
<tr style="width:100%">
<td style="width:50%" id="q2">Special Notes</td>
<td style="width:1%">:</td>
<td style="width:49%"><input type=text ng-model="personal_info_notes">{{myQuestion.notes}} </td>
</tr>
</tbody>
</table>
</div>
<center><button type=submit id="btn_evaluate">Evaluate Report</button></center>
<hr>
<hr>
</div>
</div>
</div>
</center>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src= "scripts/core/angular/angular.js"></script>
<script src= "scripts/core/angular/angular-route.js"></script>
<script src="bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="scripts/controllers/questionnaire.js" type="text/javascript"></script>
</body>
</html>
Related
Call function multiple times with different attributes
Hi I'm relatively new in angularjs and I try to create dice roller app. I have controller with 3 functions ($scope.rollDice, $scope.markDice, $scope.checkMarkedDice). I want to use $scope.rollDice multiple times with different attributes - independently. I would like to know how to modify them to work on some OOP approach. Not sure about the them. In my case if I hit button Roll 4d6 in 1st row, 2nd row is also affected and vice versa. I guess I need to transfer my rollerDice function to factory or maybe directive. But I'm not sure how to manage it. I can imagine to transfer $scope.checkMarkedDice to be var function of $scope.rollDice but I don't know how to handle $scope.markDice which has to be call from index.html so it need to be $scope or not? Plunker
Generally AngularJS is not OOP, therefore you should store individual objects in the arrays and refer to them with index. I have made what you have requested. (Warning: Heavy Snippet, here is a Plunker instead) (function() { 'use strict'; var app = angular.module('myApp', []); app.controller('myCtrl', ["$scope", function($scope) { $scope.dice_ = [ [1, 6, 4], [1, 6, 2] ]; $scope.result = [ [], [] ]; // SPECIFY SIZE / LENGTH HERE (currently: 2 items) // Roll the dice $scope.rollDice = function(min, max, count, index) { var i = 0, result = [], markedDice = $scope.checkMarkedDice(index); if (markedDice.length === 0) { while (i < count) { result[i] = { number: Math.floor(Math.random() * (max - min + 1)) + min, class: "dice" }; i += 1; } } else { while (i < count - markedDice.length) { result[i] = { number: Math.floor(Math.random() * (max - min + 1)) + min, class: "dice" }; i += 1; } angular.forEach(markedDice, function(dice) { result.splice(dice.index, 0, dice); }); } $scope.result[index] = result; }; // Mark the dice $scope.markDice = function(dice) { if (dice.class === "dice") { dice.class = "dice marked"; } else { dice.class = "dice"; } }; // Chceck if any dice is marked $scope.checkMarkedDice = function(index) { var marked = []; angular.forEach($scope.result[index], function(dice, $index) { if (dice.class.indexOf('marked') > -1) { dice.index = $index; marked.push(dice); } }); return marked; }; $scope.addDice = function(min, max, count) { $scope.result.push([]); $scope.dice_.push([min, max, count]); } $scope.removeDice = function() { $scope.result.pop(); $scope.dice_.pop(); } }]); }()); .dice { display: flex; justify-content: center; align-content: center; flex-direction: column; float: left; width: 46px; color: white; font-size: 24px; font-weight: bold; height: 46px; border: 1px solid #585858; border-radius: 15px; text-align: center; margin-right: 10px; background-color: #4573b9; } .dice:hover { background-color: #4573b9bd; cursor: pointer; } .marked { background: #00466f !important; } <!DOCTYPE html> <html ng-app="myApp"> <head> <meta charset="utf-8" /> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="app.js"></script> <link rel="stylesheet" href="style.css"> <title>Test freez reroller</title> </head> <body ng-controller="myCtrl"> <div class="container"> <h2>Basic Table</h2> <table class="table"> <thead> <tr class="flex-row"> <th class="col-md-3">Type</th> <th class="col-md-3">Action</th> <th class="col-md-6">Result</th> </tr> </thead> <tbody> <tr class="flex-row" ng-repeat="d_ in dice_ track by $index"> <td>Lorem ipsum</td> <td> <button type="button" class="btn btn-primary" ng-click="rollDice(d_[0],d_[1],d_[2],$index);">Roll {{d_[2]}}d{{d_[1]}}</button> </td> <td> <div ng-click="markDice(dice);" class="{{dice.class}}" ng-repeat="dice in result[$index] track by $index">{{dice.number}}</div> </td> </tr> </tbody> </table> 1: <input type="number" ng-model="a1"><br> 2: <input type="number" ng-model="a2"><br> 3: <input type="number" ng-model="a3"><br> <button type="button" class="btn btn-success" ng-click="addDice(a1,a2,a3)">Add</button> <button type="button" class="btn btn-danger" ng-click="removeDice()">Remove</button> </div> </body> </html>
How to display specific items in ng-repeat with ng-mouseover?
I need to show an Edit icon on a particular element, but as hovering it shows the Edit icon on each element in ng-repeat. How can I achieve it using controllerAs? Please provide me solution for the same. I'm able to achieve through normal behaviour($scope), but unable to get it through a controller. Here is the link -- > enter code herehttp://plnkr.co/edit/ETMyoDLR8HPFIZFrA90n?p=preview
Here is what you need. Instead of setting the hoverEdit with the controller use it instead with the task. var app = angular.module('plunker', []); app.controller('MainCtrl', function() { var ma = this; ma.tasks = [{ name: 'Item One' }, { name: 'The second item' }, { name: 'Three items is the best' } ]; ma.hoverIn = function(task) { task.hoverEdit = true; }; ma.hoverOut = function(task) { task.hoverEdit = false; }; }); /* Put your css in here */ li { width: 200px; list-style-type: none; padding: 6px 10px; } li:hover { background: #EEE; } .animate-show { -webkit-transition: all linear 0.5s; transition: all linear 0.5s; opacity: 1; } .animate-show.ng-hide-add, .animate-show.ng-hide-remove { display: inline-block !important; } .animate-show.ng-hide { opacity: 0; } <!DOCTYPE html> <html ng-app="plunker"> <head> <meta charset="utf-8" /> <title>AngularJS Plunker</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> </head> <body ng-controller="MainCtrl as ma"> <ul> <li ng-repeat="task in ma.tasks" ng-mouseover="ma.hoverIn(task)" ng-mouseleave="ma.hoverOut(task)"> {{task.name}} <span ng-show="task.hoverEdit" class="animate-show"> <a> <img src="https://cdn2.iconfinder.com/data/icons/freecns-cumulus/16/519584-081_Pen-16.png" alt=""> Edit </a> </span> </li> </ul> </body> </html> Hope it helps :)
you can use $index to set the index to hoverEdit ma.hoverIn = function(index){ ma.hoverEdit = index; }; ma.hoverOut = function(){ ma.hoverEdit = null; }; checking if you are hovering the index and display it using ng-show <ul> <li ng-repeat="task in ma.tasks" ng-mouseover="ma.hoverIn($index)" ng-mouseleave="ma.hoverOut()"> {{task.name}} <span ng-show="ma.hoverEdit == $index" class="animate-show"> <a> <img src="https://cdn2.iconfinder.com/data/icons/freecns-cumulus/16/519584-081_Pen-16.png" alt=""> Edit </a> </span> </li> here is the plunker
There is one more solution please have a look into this added plunker code. <body ng-controller="MainCtrl as ma"> <ul> <li ng-repeat="task in ma.tasks" ng-mouseover="ma.hoverIn(task)" ng-mouseleave="ma.hoverOut(task)"> {{task.name}} <span ng-show="task.hoverEdit" class="animate-show"> <a> <img src="https://cdn2.iconfinder.com/data/icons/freecns-cumulus/16/519584-081_Pen-16.png" alt=""> Edit </a> </span> </li> </ul> </body> var app = angular.module('plunker', ['ngAnimate']); app.controller('MainCtrl', function() { var ma=this; ma.tasks = [ {name: 'Item One', hoverEdit : false}, {name: 'The second item', hoverEdit : false}, {name: 'Three items is the best', hoverEdit : false} ]; ma.hoverIn = function(obj){ obj.hoverEdit = true; }; ma.hoverOut = function(obj){ obj.hoverEdit = false; }; });
angularjs ng-repeat with dynamic json/object
I am looking a solution for dynamic data structure(inconsistent like different property name and property length) with ng-repeat. sample code are below. $scope.data = [{ "table":[{ "employee":"name1", "value1":"10", "value2":"20" }, { "employee":"name2", "value1":"15", "value2":"30" }] }, { "table":[{ "company":"name1", "compnayValue":"12" }, { "company":"name2", "compnayValue":"12" }] }] <ul> <li ng-repeat="item in data"> <table> <tr ng-repeat="row in item.table"> <td>{{??}}</td> <td>{{??}}</td> </tr> </table> </li> </ul>
You could enumerate all properties and display their values by another ng-repeat on td: <li ng-repeat="item in data"> <table> <tr ng-repeat="row in item.table"> <td ng-repeat="(key, value) in row"> {{row[key]}} </td> </tr> </table> </li> but that would break the tabular format of data since some rows would have more tds. To prevent that you could first find out the set of all keys on all rows, do a th repeat with those first and then display them on the corresponding td below, e.g.: <th ng-repeat="propertyName in allPossiblePropertyNames"> {{propertyName}} </th> and <td ng-repeat="propertyName in allPossiblePropertyNames"> {{row[propertyName ]}} </td>
Use <tbody> to represent an object inside table array and (key,value) syntax mentioned in iterating over object properties section to iterate over it's properties like: angular.module('test', []).controller('testCtrl', function($scope) { $scope.data = [{ "table": [{ "employee": "name1", "value1": "10", "value2": "20" }, { "employee": "name2", "value1": "15", "value2": "30" }] }, { "table": [{ "company": "name1", "compnayValue": "12" }, { "company": "name2", "compnayValue": "12" }] }] }); ul { padding: 0; } ul li { list-style-type: none; margin-bottom: 10px; } table { width: 100%; table-layout: fixed; background: #ebebeb; } tbody:nth-child(odd) tr { color: #fff; background: dodgerblue; } tbody:nth-child(even) tr { color: #fff; background: hotpink; } <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="test" ng-controller="testCtrl"> <ul> <li ng-repeat="item in data"> <table> <tbody ng-repeat="row in item.table"> <tr ng-repeat="(key, value) in row"> <td> {{key}} </td> <td> {{value}} </td> </tr> </tbody> </table> </li> </ul> </div>
Check this plunker, you can define template depends on your data : https://plnkr.co/edit/fVGhKZy5gnBzuPwspy5s?p=preview Use angular filter : app.controller('MainCtrl', function($scope) { $scope.name = 'World'; $scope.data = [{ "table":[{ "employee":"name1", "value1":"10", "value2":"20" }, { "employee":"name2", "value1":"15", "value2":"30" }] }, { "table":[{ "company":"name1", "compnayValue":"12" }, { "company":"name2", "compnayValue":"12" }] }] }) .filter('isCompnay', function() { return function(input) { console.log(input.employee === undefined) return input.company ? input : undefined; }; }) .filter('isEmployee', function() { return function(input) { console.log(input.employee === undefined) return input.employee ? input : undefined; }; });
AngularJS can't fetch more than 4 records
The following code is for an AngularJS code to read data from a .txt file and echo out on the webpage. It works just fine for the entered records in the .txt file, but upon increasing the number of records above 4, the code fails to work. What could be wrong? Index.html <html> <head> <title>Angular JS Includes</title> <style> table, th , td { border: 1px solid grey; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd) { background-color: #f2f2f2; } table tr:nth-child(even) { background-color: #ffffff; } </style> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app="" ng-controller="studentController"> <table> <tr> <th>Name</th> <th>Roll No</th> <th>Percentage</th> </tr> <tr ng-repeat="student in students"> <td>{{ student.Name }}</td> <td>{{ student.RollNo }}</td> <td>{{ student.Percentage }}</td> </tr> </table> </div> <script> function studentController($scope,$http) { var url="data.txt"; $http.get(url).success( function(response) { $scope.students = response; }); } </script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> </body> Data.txt [ { "Name" : "Collin James", "RollNo" : 101, "Percentage" : "81.5%" }, { "Name" : "Michael Ross", "RollNo" : 201, "Percentage" : "70%" }, { "Name" : "Robert Flare", "RollNo" : 191, "Percentage" : "75%" }, { "Name" : "Julian Joe", "RollNo" : 111, "Percentage" : "77%" } ]
How to display "No result found" message if query result is empty in ng-tags-input?
Here is my code. If loadTags returns empty result then is there any way to show no result found message? <tags-input ng-model="tags" on-invalid-tag='test' display-property="Name" add-from-autocomplete-only="true" tabindex="3"> <auto-complete source="loadTags($query)"></auto-complete> </tags-input>
I dont know what api/data(Array) your using we have to using ng-show in ng-repeat to show show "No result found" tag in html here is the code function MyCtrl($scope, $filter) { $scope.nodata = false; $scope.items = [ {id:1, name:'John'}, {id:2, name:'Steve'}, {id:3, name:'Joey'}, {id:4, name:'Mary'}, {id:5, name:'Marylin'}]; $scope.items2 = $scope.items; $scope.$watch('search', function(val) { console.log($filter('filter')($scope.items2, val)); $scope.items = $filter('filter')($scope.items2, val); // items return for api after search if array is empty if($filter('filter')($scope.items2, val).length == 0){ // item are empty $scope.nodata = true; } else{ $scope.nodata = false; } }); }; HTML <div ng-app> <div ng-controller="MyCtrl"> <input type="text" ng-model="search"> <table> <tbody> <div ng-show="nodata">NO results found</div> <tr ng-repeat="item in items"> <td>{{item.id}}</td> <td>{{item.name}}</td> </tr> </tbody> </table> </div> </div> CSS CODE .no_rocord{border-color: #ececec; border-width: 1px; border-style: solid; border-radius: 2px; width: 250px; padding: 6px; cursor: pointer; z-index: 9999; position: absolute; margin-top: -6px; background-color: #ffffff } JS FIDDLE