AngularJS app connectivity with Mongodb using NodeJS - angularjs

This is my AngularJS app. It is working alright and taking data from an array in a controller using ng-repeat, but now I want to connect it with Mongodb using NodeJS so that it fetches data from Mongodb collection. Also, when I edit, update or delete any row, it should reflect that in Mongodb.
My AngularJS index.html
var app = angular.module("app", ["xeditable", "ngMockE2E"]);
app.service('filteredListService', function() {
this.searched = function(valLists, toSearch) {
return _.filter(valLists,
function(i) {
/* Search Text in all 3 fields */
return searchUtil(i, toSearch);
});
};
this.paged = function(valLists, pageSize) {
retVal = [];
for (var i = 0; i < valLists.length; i++) {
if (i % pageSize === 0) {
retVal[Math.floor(i / pageSize)] = [valLists[i]];
} else {
retVal[Math.floor(i / pageSize)].push(valLists[i]);
}
}
return retVal;
};
});
app.run(function(editableOptions) {
editableOptions.theme = 'bs3';
});
app.controller('Ctrl', function($scope, $filter, filteredListService) {
$scope.users = [{
id: 1,
name: 'harry potter',
lName: "Pege",
passw1: "12/12/2012",
pages: "556"
},
{
id: 2,
name: 'narnia',
lName: "Pim",
passw1: "12/12/2012",
pages: "557"
},
{
id: 3,
name: 'panchtantra',
lName: "Smith",
passw1: "1/03/2009",
pages: "556"
},
{
id: 4,
name: 'atlas',
lName: "Jones",
passw1: "2/04/1995",
pages: "888"
},
{
id: 5,
name: 'science',
lName: "Doe",
passw1: "2/04/1995",
pages: "888"
},
{
id: 6,
name: 'guiness book',
lName: "Pan",
passw1: "2/04/1995",
pages: "888"
},
{
id: 7,
name: 'panchtantra1',
lName: "Smith",
passw1: "1/03/2009",
pages: "556"
},
{
id: 8,
name: 'atlas1',
lName: "Jones",
passw1: "2/04/1995",
pages: "888"
},
{
id: 9,
name: 'science1',
lName: "Doe",
passw1: "2/04/1995",
pages: "888"
},
{
id: 10,
name: 'guiness book1',
lName: "Pan",
passw1: "2/04/1995",
pages: "888"
},
];
$scope.checkName = function(data, id) {
if (id === 2 && data !== 'narnia') {
return "Username 2 should be `narnia(case sensitive)`";
}
};
$scope.saveUser = function(data, id) {
//$scope.user not updated yet
angular.extend(data, {
id: id
});
return $http.post('/saveUser', data);
};
// remove user
$scope.removeUser = function(index) {
var index1 = index + $scope.currentPage * 4;
$scope.users.splice(index1, 1);
$scope.pagination();
};
// add user
$scope.addUser = function($event) {
$scope.currentPage = 2;
$scope.id = $scope.users.length + 1
$scope.users.push({
id: this.id,
name: 'Enter Book Name',
lName: 'Author Name',
passw1: 'Date of Publish',
pages: 'Pages'
});
$scope.pagination();
alert(users.id);
$scope.resetAll();
}
//search
$scope.pageSize = 4;
$scope.allItems = $scope.users;
$scope.reverse = false;
$scope.resetAll = function() {
$scope.filteredList = $scope.allItems;
$scope.newEmpId = '';
$scope.newName = '';
$scope.newEmail = '';
$scope.searchText = '';
$scope.currentPage = 0;
$scope.Header = ['', '', ''];
}
//pagination
$scope.pagination = function() {
$scope.ItemsByPage = filteredListService.paged($scope.filteredList, $scope.pageSize);
};
$scope.setPage = function() {
$scope.currentPage = this.n;
};
$scope.firstPage = function() {
$scope.currentPage = 0;
};
$scope.lastPage = function() {
$scope.currentPage = $scope.ItemsByPage.length - 1;
};
$scope.range = function(input, total) {
var ret = [];
if (!total) {
total = input;
input = 0;
}
for (var i = input; i < total; i++) {
if (i != 0 && i != total - 1) {
ret.push(i);
}
}
return ret;
};
$scope.sort = function(sortBy) {
$scope.resetAll();
$scope.pagination();
};
$scope.sort('name');
$scope.search = function() {
$scope.filteredList =
filteredListService.searched($scope.allItems, $scope.searchText);
if ($scope.searchText == '') {
$scope.filteredList = $scope.allItems;
}
$scope.pagination();
}
$scope.resetAll();
});
function searchUtil(x, toSearch) {
/* Search Text in all 3 fields */
return (x.name.toLowerCase().indexOf(toSearch.toLowerCase()) > -1 || x.lName.toLowerCase().indexOf(toSearch.toLowerCase()) > -1 || x.id == toSearch) ?
true : false;
}
<html>
<head>
<style type="text/css">#charset "UTF-8";[ng\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\:form{display:block;}.ng-animate-shim{visibility:hidden;}.ng-anchor{position:absolute;}</style>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="/js/lib/dummy.js"></script>
<script type="text/javascript" src="https://underscorejs.org/underscore.js"></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-sanitize.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://vitalets.github.io/angular-xeditable/dist/js/xeditable.js"></script>
<link rel="stylesheet" type="text/css" href="https://vitalets.github.io/angular-xeditable/dist/css/xeditable.css">
<script type="text/javascript" src="https://code.angularjs.org/1.5.8/angular-mocks.js"></script>
<link rel="stylesheet" type="text/css" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css"/>
<style type="text/css">
div[ng-app] {
margin: 10px;
}
.table {width: 100%
}
form[editable-form] > div {margin: 100px 0;}
</style>
</head>
<body>
<h4>Book management</h4>
<div ng-app="app" ng-controller="Ctrl">
<div class="input-group">
<input class="form-control" ng-model="searchText" placeholder="Search" type="search" ng-change="search()" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-search"></span>
</span>
</div>
<br>
<br>
<table class="table table-bordered table-hover table-condensed" id="myTable">
<tr style="font-weight: bold">
<td style="width:5%">id</td>
<td style="width:15%">Book Name</td>
<td style="width:15%">Author Name</td>
<td style="width:15%">No Of Page</td>
<td style=width:30%>Date</td>
<td style="width:25%">Edit</td>
</tr>
<tr ng-repeat="x in ItemsByPage[currentPage] | orderBy:columnToOrder:reverse">
<td>{{x.id}}</td>
<td>
<!-- editable username (text with validation) -->
<span editable-text="x.name" e-name="name" e-form="rowform" onbeforesave="checkName($data, x.id)" e-required>
{{ x.name || 'empty' }}
</span>
</td>
<td>
<!-- editable status (select-local) -->
<span editable-text="x.lName" e-name="lName" e-form="rowform">
{{ x.lName || 'empty' }}
</span>
</td>
<td>
<!-- editable group (select-remote) -->
<span editable-text="x.pages" e-name="pages" e-form="rowform" >
{{ x.pages || 'empty' }}
</span>
</td>
<td>
<span editable-text="x.passw1" e-name="passw1" e-form="rowform" >
{{x.passw1 || 'empty'}}
</span>
</td>
<td style="white-space: nowrap">
<!-- form -->
<form editable-form name="rowform" ng-show="rowform.$visible" class="form-buttons form-inline">
<button type="submit" ng-disabled="rowform.$waiting" class="btn btn-primary">
save
</button>
<button type="button" ng-disabled="rowform.$waiting" ng-click="rowform.$cancel()" class="btn btn-default">
cancel
</button>
</form>
<div class="buttons" ng-show="!rowform.$visible">
<button class="btn btn-primary" ng-click="rowform.$show()">edit</button>
<button class="btn btn-danger" ng-click="removeUser($index)">del</button>
</div>
</td>
</tr>
</table>
<button class="btn btn-default" ng-click="addUser()">Add row</button>
<br>
<ul class="pagination pagination-sm">
<li ng-class="{active:0}">First
</li>
<li ng-repeat="n in range(ItemsByPage.length)"> 1
</li>
<li>Last
</li>
</ul>
</div>
View Records
</body>
</html>

You can try learning nodejs and mongodb.

Related

Angular js - How to do strict and progressive search on same field?

I'm trying to do strict and progressive search on same fields in 2 different ways. That is when filter through drop down it should to a strict search and through input search it should do a progressive search. I tried to do it using <tr ng-repeat="x in names | filter:{name:name||dropdownFieldName:true, country:country}"> but is giving some error, Its not working.
Please check the bellow code and help me to solve this issue
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<select id="fieldDropdownHtml" ng-model="fieldSelected" ng-options="x.name for x in names" ng-change="searchOnField()">
<option value=""></option>
</select>
<table border="1" width="100%">
<tr>
<th ng-click="orderByMe('name')">Name</th>
<th ng-click="orderByMe('country')">Country</th>
</tr>
<tr>
<td><p><input type="text" ng-model="name" ng-disabled="disablese"></p>
<td><p><input type="text" ng-model="country"></p>
</td>
</tr>
<tr ng-repeat="x in names | filter:{name:name||dropdownFieldName, country:country}">
<!--tr ng-repeat="x in names | filter:{name:name||dropdownFieldName:true, country:country}" -->
<td>{{x.name}}</td>
<td>{{x.country}}</td>
</tr>
</table>
</div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.disablese = false;
$scope.names = [
{name:'Jani',country:'Norway'},
{name:'Carl',country:'Sweden'},
{name:'Margareth',country:'England'},
{name:'Hege',country:'Norway'},
{name:'Joe',country:'Denmark'},
{name:'Gustav',country:'Sweden'},
{name:'Birgit',country:'Denmark'},
{name:'Jani1',country:'England'},
{name:'Jani',country:'Norway'}
];
$scope.searchOnField = function() {
var e = document.getElementById("fieldDropdownHtml");
var strUser = e.options[e.selectedIndex].text;
angular.forEach($scope.names, function(dsElement) {
if (dsElement.name === strUser) {
$scope.dropdownFieldName = dsElement.name;
console.log($scope.dropdownFieldName);
}
if(document.getElementById('fieldDropdownHtml').selectedIndex == 0){
$scope.dropdownFieldName= undefined;
}
if(document.getElementById('fieldDropdownHtml').selectedIndex != 0){
$scope.disablese = true;
$scope.name = "";
}
else{
$scope.disablese = false;
}
});
}
});
</script>
</body>
</html>
Additional to Allabakash answer, you can use this code to your controller to make it simpler and minimize vanilla JavaScript codes:
angular
.module('myApp', [])
.controller('namesCtrl', function ($scope) {
$scope.disablese = false;
$scope.names = [
{ name: 'Jani', country: 'Norway' },
{ name: 'Carl', country: 'Sweden' },
{ name: 'Margareth', country: 'England' },
{ name: 'Hege', country: 'Norway' },
{ name: 'Joe', country: 'Denmark' },
{ name: 'Gustav', country: 'Sweden' },
{ name: 'Birgit', country: 'Denmark' },
{ name: 'Jani1', country: 'England' },
{ name: 'Jani', country: 'Norway' }
];
$scope.searchOnField = function () {
if ($scope.fieldSelected) {
$scope.dropdownFieldName = $scope.fieldSelected.name;
$scope.name = null;
$scope.disablese = true;
} else {
$scope.dropdownFieldName = undefined;
$scope.disablese = false;
}
};
});
You can achieve this by separating filters like below.
ng-repeat="x in names | filter:{name:name||dropdownFieldName}: disablese | filter: { country:country }"
Hope this helps.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<select id="fieldDropdownHtml" ng-model="fieldSelected" ng-options="x.name for x in names" ng-change="searchOnField()">
<option value=""></option>
</select>
<table border="1" width="100%">
<tr>
<th ng-click="orderByMe('name')">Name</th>
<th ng-click="orderByMe('country')">Country</th>
</tr>
<tr>
<td><p><input type="text" ng-model="name" ng-disabled="disablese"></p>
<td><p><input type="text" ng-model="country"></p>
</td>
</tr>
<tr ng-repeat="x in names | filter:{name:name||dropdownFieldName}: disablese | filter: { country:country }">
<!--tr ng-repeat="x in names | filter:{name:name||dropdownFieldName:true, country:country}" -->
<td>{{x.name}}</td>
<td>{{x.country}}</td>
</tr>
</table>
</div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.disablese = false;
$scope.names = [
{name:'Jani',country:'Norway'},
{name:'Carl',country:'Sweden'},
{name:'Margareth',country:'England'},
{name:'Hege',country:'Norway'},
{name:'Joe',country:'Denmark'},
{name:'Gustav',country:'Sweden'},
{name:'Birgit',country:'Denmark'},
{name:'Jani1',country:'England'},
{name:'Jani',country:'Norway'},
{name:'Jani',country:'Harway'}
];
$scope.searchOnField = function() {
var e = document.getElementById("fieldDropdownHtml");
var strUser = e.options[e.selectedIndex].text;
angular.forEach($scope.names, function(dsElement) {
if (dsElement.name === strUser) {
$scope.dropdownFieldName = dsElement.name;
console.log($scope.dropdownFieldName);
}
if(document.getElementById('fieldDropdownHtml').selectedIndex == 0){
$scope.dropdownFieldName= undefined;
}
if(document.getElementById('fieldDropdownHtml').selectedIndex != 0){
$scope.disablese = true;
$scope.name = "";
}
else{
$scope.disablese = false;
}
});
}
});
</script>
</body>
</html>

use angular.js to get data from a web endpoint

I need to use angular in order to get data from a web endpoint to fill this table. I have a list created with random names, but I need it to filled with data from a link instead. I still need to create the social media links as well.
Either way, can someone show me how to do it keeping in mind that I don't know much about angular at all. thank you.
html:
<!DOCTYPE html>
<html>
<head>
<title>Angular JS </title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script type="text/javascript" src="folder/main.js"></script>
<script src="http://code.angularjs.org/1.4.8/angular.js"></script>
<script src="http://code.angularjs.org/1.4.8/angular-resource.js"></script>
<script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.11.0.js"></script>
<link rel="stylesheet" type="text/css" href="css/main.css">
</head>
<body ng-app="MyForm">
<div ng-controller="myCtrl">
<h3>List students</h3>
<div class="container-fluid">
<pre>Click header link to sort, input into filter text to filter</pre>
<hr />
<table class="table table-striped">
<thead>
<tr>
<th>Edit</th>
<th>
ID
</th>
<th> Name </th>
<th>Social Media </th>
</tr>
</thead>
<tbody>
<tr>
<td>Filter =>></td>
<td> <input type="text" ng-model="search.name" /></td>
<td> <input type="text" ng-model="search.age" /> </td>
<td><input type="text" ng-model="search.gender" /> </td>
</tr>
<tr ng-repeat="user in students | orderBy:predicate:reverse | filter:paginate| filter:search" ng-class-odd="'odd'">
<td>
<button class="btn">
Edit
</button>
</td>
<td>{{ user.name}}</td>
<td>{{ user.age}}</td>
<td>{{ user.gender}}</td>
</tr>
</tbody>
</table>
<pagination total-items="totalItems" ng-model="currentPage"
max-size="5" boundary-links="true"
items-per-page="numPerPage" class="pagination-sm">
</pagination>
</div>
</div>
</body>
</html>
js:
<script>
var app = angular.module('MyForm', ['ui.bootstrap', 'ngResource']);
app.controller('myCtrl', function ($scope) {
$scope.predicate = 'name';
$scope.reverse = true;
$scope.currentPage = 1;
$scope.order = function (predicate) {
$scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
$scope.predicate = predicate;
};
$scope.students = [
{ name: 'Kevin', age: 25, gender: 'boy' },
{ name: 'John', age: 30, gender: 'girl' },
{ name: 'Laura', age: 28, gender: 'girl' },
{ name: 'Joy', age: 15, gender: 'girl' },
{ name: 'Mary', age: 28, gender: 'girl' },
{ name: 'Peter', age: 95, gender: 'boy' },
{ name: 'Bob', age: 50, gender: 'boy' },
{ name: 'Erika', age: 27, gender: 'girl' },
{ name: 'Patrick', age: 40, gender: 'boy' },
{ name: 'Tery', age: 60, gender: 'girl' }
];
$scope.totalItems = $scope.students.length;
$scope.numPerPage = 5;
$scope.paginate = function (value) {
var begin, end, index;
begin = ($scope.currentPage - 1) * $scope.numPerPage;
end = begin + $scope.numPerPage;
index = $scope.students.indexOf(value);
return (begin <= index && index < end);
};
});
</script>
the data looks like this:
{"id":"11","name":"A Cooperativa","full_address":"Rua Bar\u00e3o de Viamonte 5, 2400-262 Leiria","location":"Leiria","council":"Leiria","country":"Portugal","lat":"39.7523042","lng":"-8.7825576","type":"various","facebook":"https:\/\/www.facebook.com\/pages\/A-Cooperativa-MerceariaTasca\/1559630810945570","facebook_id":"","gmaps":"https:\/\/www.google.pt\/maps\/place\/R.+Bar%C3%A3o+de+Viamonte+5,+2410+Leiria\/#39.7523042,-8.7825576,17z\/data=!3m1!4b1!4m2!3m1!1s0xd2273a29462db11:0x49a3f9a45cd9eb80","tripadvisor":"http:\/\/www.tripadvisor.com\/Restaurant_Review-g230085-d8154189-Reviews-A_Cooperativa-Leiria_Leiria_District_Central_Portugal.html","zomato":"","website":"","email":"cooperativa.tasca#hotmail.com","telephone":"912635324","active":"1","updated":"2015-08-17 09:01:05"}
I'm not sure if I did get this right, but:
You want to get the students from a web endpoint as json?
Then you would write something like this in angular:
app.controller('myCtrl', function ($scope, $http) {
...
$scope.students = [];
$scope.totalItems = 0;
$http.get('https://www.domain.com/api/resource')
.then(function success(response) {
$scope.students = response.data;
$scope.totalItems = $scope.students.length;
}, function failed(reason) {console.log(reason);})
...
});
But you should use separated files, services etc.

list.js sorting and view change not working with angular

I have artists information in the angular scope and used ng-repeat to repeat to list all artist info in the template. I am trying to sort (name, title, label, view) data using list.js. I have installed list.js using bower and mentioned the source in the html template <script src="/static/vendors/list.js/dist/list.min.js"></script>.
I am exactly trying to replicate this codepen but with angular.
I am aware about angular sorting!
Problem: Sorting and view change doesn't seems to work
<div id="artists">
<input class="search" placeholder="Search" />
<button class="sort" data-sort="artist-name">Sort by name </button>
<button class="sort" data-sort="album-title">Sort by Project </button>
<button class="sort" data-sort="record-label">Sort by Label </button>
<button class="sort" id="viewSwitch"> Change View </button>
<ul class="list" id="list">
<li ng-repeat="item in artists >
<img src="http://placehold.it/120x120" alt="#" />
<h3 class="artist-name">{{item.artist-name}}</h3>
<p class="album-title">{{item.artist-title}}</p>
<p class="record-label">{{item.record-label}}</p>
</li> </ul> </div>
<script> var options = { valueNames: [ 'artist-name', 'artist-title', 'record-label' ] };
var artistList = new List('artists', options);
// View Switcher
$('#viewSwitch').on('click',function(e) {
if ($('ul').hasClass('grid')) {
$('ul').removeClass('grid').addClass('list');
}
else if($('ul').hasClass('list')) {
$('ul').removeClass('list').addClass('grid');
} }); </script>
angular.module("stack", [])
.controller("move", function($scope) {
var count = 0;
var count1 = 0;
var details = document.getElementsByClassName('details');
$scope.friends = [{ name: 'John', phone: '555-1212', age: 10 },
{ name: 'Mary', phone: '555-9876', age: 19 },
{ name: 'Mike', phone: '555-4321', age: 21 },
{ name: 'Adam', phone: '555-5678', age: 35 },
{ name: 'Julie', phone: '555-8765', age: 29 }
];
$scope.sort = '-age';
$scope.change = function() {
count++;
if (count % 2 !== 0) {
$scope.sort = 'age';
} else {
$scope.sort = '-age';
}
}
$scope.changeView = function() {
count1++;
if (count1 % 2 !== 0) {
for (var i = 0; i < details.length; i++) {
details[i].style.width = 10 + '%';
details[i].style.display = 'inline-block';
}
} else {
for (var i = 0; i < details.length; i++) {
details[i].style.width = 10 + '%';
details[i].style.display = 'block';
}
}
}
});
<!DOCTYPE html>
<html ng-app="stack">
<head>
<title>stack</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
</head>
<body ng-controller="move">
<div ng-repeat="friend in friends | orderBy:sort" class="details">
<h3>{{friend.name}}</h3>
<p>{{friend.phone}}</p>
<p>{{friend.age}}</p>
</div>
<button ng-click="change()">sort by age</button>
<button ng-click="changeView()">change view</button>
<script type="text/javascript" src="controller.js"></script>
</body>
</html>
i have added the basic code for sorting and the change view.Do you need the whole solution?
list.js need to run after angular has returned your last data. so in your ng-repeat do this. his will check when the last item has been rendered
ng-init="$last ? doFilter() : angular.noop()"
now you need to add the filter function to your code like this
$scope.doFilter = function () {
var options = { valueNames: [ 'artist-name', 'artist-title', 'record-label' ] };
var artistList = new List('artists', options);
};

Angular: Uncaught ReferenceError: myFunction is not defined

I'm creating a contacts list and i'm using Angular for the first time.
I created an attribute directive for the table rows (that i use inside the table tag), in which i add a controller to handle click on a button, that deletes the row removing it from the table.
All works well, but i get an error in the browser console.
Here you can see the output of my source code:
When i try to delete a contact (i press on the button with the trash as icon) it works, but in the Chrome console i get this error:
Uncaught ReferenceError: delUser is not defined
You can see it here:
Here is my code:
index.html
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8">
<title>Rubrica</title>
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</head>
<body ng-controller="myCtrl">
<section id="panel">
<button class="panel_btn" ng-click="showHideAdd()"><i class="fa fa-plus"></i> Aggiungi</button>
<button class="panel_btn" ng-click="showHideSearch()"><i class="fa fa-search"></i> Cerca</button>
</section>
<section id="list">
<table width="50%">
<thead>
<tr>
<th>Nome<span ng-show="sortType == 'name' && !sortReverse" class="fa fa-caret-down"></span><span ng-show="sortType == 'name' && sortReverse" class="fa fa-caret-up"></span></th>
<th>Cognome<span ng-show="sortType == 'surname' && !sortReverse" class="fa fa-caret-down"></span><span ng-show="sortType == 'surname' && sortReverse" class="fa fa-caret-up"></span></th>
<th>Telefono<span ng-show="sortType == 'phone' && !sortReverse" class="fa fa-caret-down"></span><span ng-show="sortType == 'phone' && sortReverse" class="fa fa-caret-up"></span></th>
<th>Operazioni</th>
</tr>
</thead>
<tbody>
<tr ng-hide="isSearchVisible">
<td><input name="nameSearch" placeholder="Cerca nome" ng-model="search.name"></input></td>
<td><input name="surnameSearch" placeholder="Cerca cognome" ng-model="search.surname"></input></td>
<td><input name="phoneSearch" placeholder="Cerca telefono" ng-model="search.phone"></input></td>
</tr>
<tr userdir item="user" onclick="delUser" ng-repeat="user in users | orderBy:sortType:sortReverse | filter:search">
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="3">Totale utenti: {{getTotal()}}</td>
</tr>
</tfoot>
</table>
</section>
<section id="tools">
<form name="addForm" ng-show="isAddVisible" novalidate>
<p>Compila tutti i campi</p>
<input type="text" name="nameToAdd" placeholder="Nome" ng-model="formName" required ng-minlength="3"><br /><small ng-show="isInvalid && (addForm.nameToAdd.$error.required || addForm.nameToAdd.$error.minlength)">Il nome deve avere almeno 3 lettere</small><br />
<input type="text" name="surnameToAdd" placeholder="Cognome" ng-model="formSurname" required ng-minlength="3"><br /><small ng-show="isInvalid && (addForm.surnameToAdd.$error.required || addForm.surnameToAdd.$error.minlength)">Il cognome deve avere almeno 3 lettere</small><br />
<input type="tel" name="phoneToAdd" placeholder="Telefono" ng-model="formPhone" required ng-pattern="/^\d{2,4}/\d{5,8}/"><br /><small ng-show="isInvalid && (addForm.phoneToAdd.$error.required || addForm.phoneToAdd.$error.pattern)">Inserisci un numero di telefono valido</small><br />
<button ng-click="add()"><i class="fa fa-save fa-lg"></i> Salva</button>
</form>
<form name="searchForm" ng-submit="search()" ng-show="isSearchVisible" novalidate>
<p>Cerca utenti</p>
<input type="text" name="stringToFind" placeholder="Cerca..." ng-model="search.$" required><br />
</form>
</section>
</body>
</html>
app.js
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', ['$scope', '$timeout', function($scope, $timeout) {
$scope.sortType = 'name';
$scope.sortReverse = false;
$scope.isInvalid = false;
$scope.users = [{
name: 'Mario',
surname: 'Rossi',
phone: '084/8465645'
}, {
name: 'Giuseppe',
surname: 'Bianchi',
phone: '06/548484'
}, {
name: 'Luca',
surname: 'Verde',
phone: '0984/3214867'
}, {
name: 'Luigi',
surname: 'Roma',
phone: '0775/3214867'
}];
$scope.getTotal = function() {
return $scope.users.length;
};
$scope.add = function() {
if ($scope.addForm.$valid) {
$scope.users.push({
name: $scope.formName,
surname: $scope.formSurname,
phone: $scope.formPhone
});
$scope.formName = '';
$scope.formSurname = '';
$scope.formPhone = '';
} else {
$scope.isInvalid = true;
}
};
$scope.isAddVisible = false;
$scope.showHideAdd = function() {
$scope.isAddVisible = $scope.isAddVisible ? false : true;
$scope.isSearchVisible = false;
};
$scope.isSearchVisible = false;
$scope.showHideSearch = function() {
$scope.isSearchVisible = $scope.isSearchVisible ? false : true;
$scope.isAddVisible = false;
};
$scope.delUser = function(user) {
var index = $scope.users.indexOf(user);
$scope.users.splice(index, 1);
};
}]);
myApp.directive('userdir', function() {
return {
restrict: 'A',
templateUrl: 'views/userRow.html',
controller: function($scope) {
$scope.delete = function() {
$scope.onclick($scope.item);
};
},
controllerAs: 'ctrl',
scope: {
item: '=',
onclick: '='
}
};
});
userRow.html
<tr>
<td>{{item.name}}</td>
<td>{{item.surname}}</td>
<td>{{item.phone}}</td>
<td><button ng-click="delete()"><i class="fa fa-trash"></i></button>
</tr>
Renaming onclick to any other word inside my directive's scope makes it working.
The glitch may happen because onclick is a reserved word for HTML.
It looks like your "ng-click=delete()" already calls the delUser function.
Why do you need the onclick="delUser" in index.html?
Also if this a function should it be onclick="delUser()"?

How to modify row content in angular js?

HI i Learning Angular js and i have created a project.
All most i have do but i m face one problum .
My Data is repeat throw tr and i have inline editable option Type, Description, Priority
if i have click in both link than show to editable mode but show all i want to show only one how to do this
HTML Code
<body ng-app="myApp" ng-controller="myCtrl">
<table class="table ">
<tbody>
<tr class="list-row" ng-repeat="form in todoData">
<td class="list-row-content">
<p>
<a>{{form.title}}</a>
</p>
<span>
Type: <a ng-show="!typeAction" ng-click="selectTypeAction($index)">{{selectedAction.label}}</a>
<select ng-change="changeTypeAction()" ng-show="typeAction" ng-model="selectedAction" ng-options="opt as opt.label for opt in options"></select>
</span>
<span class="tag-sec">
Description: <a ng-show="!typeDescAction" ng-click="desTypeAction($index)">{{desType}}</a>
<input type="text" value="" ng-show="typeDescAction" ng-model="desType" ng-blur="changeDesAction($index)" />
</span>
<span class="tag-sec">
Priority: <a ng-show="!typePriAction" ng-click="priTypeAction($index)">{{priAction.label}}</a>
<select ng-change="changePriTypeAction()" ng-show="typePriAction" ng-model="priAction" ng-options="opt as opt.label for opt in priOptions"></select>
</span>
</td>
</tr>
</tbody>
</table>
</body>
Angular jS code
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function($scope){
/* ************************************************ */
$scope.todoData = [
{'title':'Create Google Logo'},
{'title':'Talk to XYZ about Google'},
{'title':'Testing Google Coding'},
{'title':'Create Documentaion about Google'},
{'title':'Create Client Sample form'},
{'title':'Modify Top Navigation'},
{'title':'Change Footer text and color'},
{'title':'Redesign Google Dashboard'}
]
$scope.options = [
{ label: 'Action Item', value: 1 },
{ label: 'Defect', value: 2 },
{ label: 'Meeting Invite', value: 3 },
{ label: 'Issue', value: 4 },
{ label: 'Enhancement', value: 5 },
{ label: 'Risk', value: 6 },
{ label: 'Proposal', value: 7 }
];
$scope.selectedAction =$scope.options[1];
$scope.selectTypeAction = function(index){
console.log(index);
$scope.typeAction = true;
};
$scope.changeTypeAction = function(){
$scope.typeAction = false;
}
$scope.desType = 'Google logo needs a new concept';
$scope.desTypeAction = function(idx){
$scope.typeDescAction = true;
}
$scope.changeDesAction = function(idx){
$scope.typeDescAction = false;
}
$scope.priOptions = [
{ label: 'High', value: 1 },
{ label: 'Medium', value: 2 },
{ label: 'Low', value: 3 }
];
$scope.priAction =$scope.priOptions[1];
$scope.priTypeAction = function(index){
console.log(index);
$scope.typePriAction = true;
};
$scope.changePriTypeAction = function(){
$scope.typePriAction = false;
}
/* ************************************************ */
});
[Plunker URL][1]
Plunker Link
Try this Way go by index by index not as global scope
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function($scope){
/* ************************************************ */
$scope.todoData = [
{'title':'Create google Logo','discription':'google logo needs a new concept'},
{'title':'Talk to Sandeep about google','discription':'google logo needs a new concept'},
{'title':'Testing google Coding','discription':'google logo needs a new concept'},
{'title':'Create Documentaion about google','discription':'google logo needs a new concept'},
{'title':'Create Client Sample form','discription':'google logo needs a new concept'},
{'title':'Modify Top Navigation','discription':'google logo needs a new concept'},
{'title':'Change Footer text and color','discription':'google logo needs a new concept'},
{'title':'Redesign google Dashboard','discription':'google logo needs a new concept'}
]
$scope.options = [
{ label: 'Action Item', value: 1 },
{ label: 'Defect', value: 2 },
{ label: 'Meeting Invite', value: 3 },
{ label: 'Issue', value: 4 },
{ label: 'Enhancement', value: 5 },
{ label: 'Risk', value: 6 },
{ label: 'Proposal', value: 7 }
];
$scope.selectedAction =$scope.options[1];
$scope.selectTypeAction = function(index){
$scope.todoData[index].typeAction = true;
};
$scope.changeTypeAction = function(index){
$scope.todoData[index].typeAction = false;
}
$scope.desTypeAction = function(idx){
$scope.todoData[idx].typeDescAction = true;
}
$scope.changeDesAction = function(idx){
$scope.todoData[idx].typeDescAction = false;
}
$scope.priOptions = [
{ label: 'High', value: 1 },
{ label: 'Medium', value: 2 },
{ label: 'Low', value: 3 }
];
$scope.priAction = $scope.priOptions[1];
$scope.priTypeAction = function(index){
$scope.todoData[index].typePriAction = true;
};
$scope.changePriTypeAction = function(index){
$scope.todoData[index].typePriAction= false;
}
/* ************************************************ */
});
HTML CODE
<tr ng-repeat="form in todoData">
<td >
<p><a>{{form.title}}</a></p>
<span class="tag-sec">
Type: <a ng-show="!form.typeAction" ng-click="selectTypeAction($index)">{{selectedAction.label}}</a>
<select ng-change="changeTypeAction($index)" ng-show="form.typeAction" ng-model="selectedAction" ng-options="opt as opt.label for opt in options"></select>
</span>
<span class="tag-sec">
Description: <a ng-show="!form.typeDescAction" ng-click="desTypeAction($index)">{{form.discription}}</a>
<input type="text" ng-show="form.typeDescAction" ng-model="form.discription" ng-blur="changeDesAction($index)" />
</span>
<span class="tag-sec">
Priority: <a ng-show="!form.typePriAction" ng-click="priTypeAction($index)">{{priAction.label}}</a>
<select ng-change="changePriTypeAction($index)" ng-show="form.typePriAction" ng-model="priAction" ng-options="opt as opt.label for opt in priOptions"></select>
</span>
</td>
</tr>
Plunker Demo URL
Here is plunker for you.
You should keep flag for every individual properties, so define array for these flag like this,
$scope.typeAction = [];
$scope.typeDescAction = [];
$scope.typePriAction = [];
and set them by using $index property of ng-repeat, for example
ng-show="!typeAction[$index]"
and you should edit your functions by sending index all time, for example,
$scope.changeTypeAction = function(index){
$scope.typeAction[index] = false;
}
I have the simple one catch the context (using 'this') of the particular element and set the local variable of ng -repeat typeAction.
<!DOCTYPE html>
<html>
<head>
<link data-require="bootstrap-css#*" data-semver="3.3.1" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
<script data-require="angular.js#*" data-semver="1.4.0-beta.5" src="https://code.angularjs.org/1.4.0-beta.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<table class="table ">
<tbody>
<tr class="list-row" ng-repeat="form in todoData">
<td class="list-row-content">
<p>
<a>{{form.title}}</a>
</p>
<span>
Type: <a ng-show="!typeAction" ng-click="selectTypeAction($index,this)">{{selectedAction.label}}</a>
<select ng-change="changeTypeAction(this)" ng-show="typeAction" ng-model="selectedAction" ng-options="opt as opt.label for opt in options"></select>
</span>
<span class="tag-sec">
Description: <a ng-show="!typeDescAction" ng-click="desTypeAction($index,this)">{{desType}}</a>
<input type="text" value="" ng-show="typeDescAction" ng-model="desType" ng-blur="changeDesAction($index,this)" />
</span>
<span class="tag-sec">
Priority: <a ng-show="!typePriAction" ng-click="priTypeAction($index,this)">{{priAction.label}}</a>
<select ng-change="changePriTypeAction(this)" ng-show="typePriAction" ng-model="priAction" ng-options="opt as opt.label for opt in priOptions"></select>
</span>
</td>
</tr>
</tbody>
</table>
</body>
</html>
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function($scope){
/* ************************************************ */
$scope.todoData = [
{'title':'Create Google Logo'},
{'title':'Talk to XYZ about Google'},
{'title':'Testing Google Coding'},
{'title':'Create Documentaion about Google'},
{'title':'Create Client Sample form'},
{'title':'Modify Top Navigation'},
{'title':'Change Footer text and color'},
{'title':'Redesign Google Dashboard'}
]
$scope.options = [
{ label: 'Action Item', value: 1 },
{ label: 'Defect', value: 2 },
{ label: 'Meeting Invite', value: 3 },
{ label: 'Issue', value: 4 },
{ label: 'Enhancement', value: 5 },
{ label: 'Risk', value: 6 },
{ label: 'Proposal', value: 7 }
];
$scope.selectedAction =$scope.options[1];
$scope.selectTypeAction = function(index,context){
console.log(index);
context.typeAction = true;
};
$scope.changeTypeAction = function(context){
context.typeAction = false;
}
$scope.desType = 'Google logo needs a new concept';
$scope.desTypeAction = function(idx,context){
context.typeDescAction = true;
}
$scope.changeDesAction = function(idx,context){
context.typeDescAction = false;
}
$scope.priOptions = [
{ label: 'High', value: 1 },
{ label: 'Medium', value: 2 },
{ label: 'Low', value: 3 }
];
$scope.priAction =$scope.priOptions[1];
$scope.priTypeAction = function(index,context){
console.log(index);
context.typePriAction = true;
};
$scope.changePriTypeAction = function(context){
context.typePriAction = false;
}
/* ************************************************ */
});
Plunker
Use "This" object
Past this HTML COde
<!DOCTYPE html>
<html>
<head>
<link data-require="bootstrap-css#*" data-semver="3.3.1" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
<script data-require="angular.js#*" data-semver="1.4.0-beta.5" src="https://code.angularjs.org/1.4.0-beta.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<table class="table ">
<tbody>
<tr class="list-row" ng-repeat="form in todoData">
<td class="list-row-content">
<p>
<a>{{form.title}}</a>
</p>
<span>
Type: <a ng-show="!typeAction" ng-click="selectTypeAction($index,this)">{{selectedAction.label}}</a>
<select ng-change="changeTypeAction(this)" ng-show="typeAction" ng-model="selectedAction" ng-options="opt as opt.label for opt in options"></select>
</span>
<span class="tag-sec">
Description: <a ng-show="!typeDescAction" ng-click="desTypeAction($index,this)">{{desType}}</a>
<input type="text" value="" ng-show="typeDescAction" ng-model="desType" ng-blur="changeDesAction($index,this)" />
</span>
<span class="tag-sec">
Priority: <a ng-show="!typePriAction" ng-click="priTypeAction($index,this)">{{priAction.label}}</a>
<select ng-change="changePriTypeAction(this)" ng-show="typePriAction" ng-model="priAction" ng-options="opt as opt.label for opt in priOptions"></select>
</span>
</td>
</tr>
</tbody>
</table>
</body>
</html>
Past this js code
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function ($scope) {
/* ************************************************ */
$scope.todoData = [
{ 'title': 'Create Google Logo' },
{ 'title': 'Talk to XYZ about Google' },
{ 'title': 'Testing Google Coding' },
{ 'title': 'Create Documentaion about Google' },
{ 'title': 'Create Client Sample form' },
{ 'title': 'Modify Top Navigation' },
{ 'title': 'Change Footer text and color' },
{ 'title': 'Redesign Google Dashboard' }
]
$scope.options = [
{ label: 'Action Item', value: 1 },
{ label: 'Defect', value: 2 },
{ label: 'Meeting Invite', value: 3 },
{ label: 'Issue', value: 4 },
{ label: 'Enhancement', value: 5 },
{ label: 'Risk', value: 6 },
{ label: 'Proposal', value: 7 }
];
$scope.selectedAction = $scope.options[1];
$scope.selectTypeAction = function (index, objVal) {
console.log(index);
objVal.typeAction = true;
};
$scope.changeTypeAction = function (objVal) {
objVal.typeAction = false;
}
$scope.desType = 'Google logo needs a new concept';
$scope.desTypeAction = function (idx, objVal) {
objVal.typeDescAction = true;
}
$scope.changeDesAction = function (idx, objVal) {
objVal.typeDescAction = false;
}
$scope.priOptions = [
{ label: 'High', value: 1 },
{ label: 'Medium', value: 2 },
{ label: 'Low', value: 3 }
];
$scope.priAction = $scope.priOptions[1];
$scope.priTypeAction = function (index, objVal) {
console.log(index);
objVal.typePriAction = true;
};
$scope.changePriTypeAction = function (objVal) {
objVal.typePriAction = false;
}
/* ************************************************ */
});
Working Demo

Resources