dynamic pagination in angular - html

I built an angular app that have table with data. I show it with the pagination concept, 3 lines in a page, and it works, but when I add new data(user) to the table, it doesn't adds page in the pagination bar.
the angular code:
app = angular.module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap']);
app.controller('AppCtrl', function($scope, $modal, $log ) {
$scope.Users = [{
'userN': 'Ariel1',
'PassW': 'Aa123456',
'Name': 'Ariel',
'LastName': 'Livshits'
}, {
'userN': 'Ariel2',
'PassW': 'Aa123456',
'Name': 'Ariel',
'LastName': 'Livshits'
}, {
'userN': 'Ariel3',
'PassW': 'Aa123456',
'Name': 'Ariel',
'LastName': 'Livshits'
}, {
'userN': 'Ariel4',
'PassW': 'Aa123456',
'Name': 'Ariel',
'LastName': 'Livshits'
}, {
'userN': 'Ariel5',
'PassW': 'Aa123456',
'Name': 'Ariel',
'LastName': 'Livshits'
}, {
'userN': 'Ariel6',
'PassW': 'Aa123456',
'Name': 'Ariel',
'LastName': 'Livshits'
}, {
'userN': 'Ariel6',
'PassW': 'Aa123456',
'Name': 'Ariel',
'LastName': 'Livshits'
}, {
'userN': 'Ariel6',
'PassW': 'Aa123456',
'Name': 'Ariel',
'LastName': 'Livshits'
}];
$scope.User = {
'username': '',
'Password': '',
'connected': false
};
$scope.viewby = 3;
$scope.totalItems = $scope.Users.length;
$scope.currentPage = 1;
$scope.itemsPerPage = $scope.viewby;
$scope.maxSize = ($scope.Users.length / 3) + 1; //Number of pager buttons to show
$scope.setPage = function (pageNo) {
$scope.currentPage = pageNo;
};
$scope.pageChanged = function() {
console.log('Page changed to: ' + $scope.currentPage);
};
$scope.setItemsPerPage = function(num) {
$scope.itemsPerPage = num;
$scope.currentPage = 1; //reset to first paghe
};
$scope.openR = function() {
var modalInstance = $modal.open({
templateUrl: 'table.html',
controller: 'ModalInstanceCtrl'
});
modalInstance.result.then(function(newUser) {
$scope.Users.push(newUser);
}, function() {
$log.info('Modal dismissed at: ' + new Date());
});
};
$scope.openC = function() {
var modalInstance = $modal.open({
templateUrl: 'connect.html',
controller: 'ModalInstanceCtrl'
});
modalInstance.result.then(function(conUser) {
$scope.User = conUser;
}, function() {
$log.info('Modal dismissed at: ' + new Date());
});
};
});
// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $modal service used above.
app.controller('ModalInstanceCtrl', function($scope, $modalInstance) {
$scope.okR = function() {
$modalInstance.close({
'userN': $scope.userN,
'PassW': $scope.PassW,
'Name': $scope.Name,
'LastName': $scope.LastName
});
};
$scope.okC = function() {
$modalInstance.close({
'username': $scope.username,
'Password': $scope.password,
'connected': true
});
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
});
the html code :
<!doctype html>
<html ng-app="ui.bootstrap.demo">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular-animate.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.13.3.js"></script>
<script src="app.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div ng-controller="AppCtrl" >
<button type="button" class="btn btn-default" ng-click="openR()"> add user </button>
<button type="button" class="btn btn-default" ng-click="openC()"> connect </button>
<div class="btn btn-success" ng-show="User.connected">{{User.username}} is connected</div>
<table>
<thead>
<th class="col-lg-3">Username</th>
<th class="col-lg-3">Password</th>
<th class="col-lg-3">First name</th>
<th class="col-lg-3">Last name</th>
</thead>
<tbody>
<tr ng-repeat="User in Users.slice(((currentPage-1)*itemsPerPage), ((currentPage)*itemsPerPage))">
<td class="col-lg-3">{{User.userN}}</td>
<td class="col-lg-3">{{User.PassW}}</td>
<td class="col-lg-3">{{User.Name}}</td>
<td class="col-lg-3">{{User.LastName}}</td>
</tr>
</tbody>
</table>
<div >
<pagination total-items="totalItems" ng-model="currentPage" ng-change="pageChanged()" class="pagination-sm" items-per-page="itemsPerPage"></pagination>
</div>
</div>
<script type="text/ng-template" id="table.html">
<form ng-submit="okR()">
<div class="modal-header" >
<h3>users</h3>
</div>
<div class="modal-body">
<div class="panel-body">
<div class="form-group">
<label>Username :</label>
<input type="text" placeholder="Ariel73" ng-model="userN">
</div>
<div class="form-group">
<label>Password :</label>
<input type="text" placeholder="Aa123456" ng-model="PassW">
</div>
<div class="form-group">
<label>First name :</label>
<input type="text" placeholder="Ariel" ng-model="Name">
</div>
<div class="form-group">
<label>Last name :</label>
<input type="text" placeholder="Livshits" ng-model="LastName">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</script>
<script type="text/ng-template" id="connect.html">
<form ng-submit="okC()">
<div class="modal-header" >
<h3>users</h3>
</div>
<div class="modal-body">
<div class="panel-body">
<div class="form-group">
<label>Username :</label>
<input type="text" placeholder="Ariel73" ng-model="username">
</div>
<div class="form-group">
<label>Password :</label>
<input type="text" placeholder="Aa123456" ng-model="password">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</script>
</body>
</html>

Is "pagination" your own directive?
The way angular works is it will run your "controller" code only once when the directive loads.
You can do one of two things. Add a "watch" in the "pagination" controller to update when one of your "scope variables" on the directive pagination updates. Or set up an event(broadcast or emit, and an on) that lets pagination know to update when users updates.
Here is a link to documentation of setting up a $watch variable.

Related

How to send a picture and name to the database?

Stack vue.js + laravel5.7 I need to load the image and name into the database using axios tools in the component. There is a problem in the code, I can’t understand what is wrong.
Separately, the name downloaded and displayed, it was useful to screw the picture, everything broke. The server on php7.1
Here is my template
<form v-on:submit.prevent="submitCategory()" class="col s12 l12">
<div class="col s12 l3">
<div class="input-field ">
<input id="name" type="text" v-model="posts.name">
<label for="name">Название</label>
<div class="file-field input-field">
<div class="btn">
<span>Загрузить изображение</span>
<input type="file" v-on:change="onFileChange">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text">
</div>
</div>
</div>
<div>
<button class="waves-effect waves-light btn">
Сохранить изменения
</button>
</div>
</div>
<div class="col s12 l3 center">
<div v-if="!posts.image">
<img src="/images/No_image.png" style="height: 200px"/>
</div>
<div v-else>
<img :src="posts.image" style="height: 200px"/>
<button #click="removeImage" class="btn">Удалить изо</button>
</div>
</div>
</form>
And this is my script
<script>
import axios from 'axios';
export default {
data: function() {
return {
posts: {
name:'',
image:'',
},
errors: []
}
},
methods:{
submitCategory() {
axios.post(`/categories`, this.posts)
.then(response => {
console.log(response)
//this.$router.push({path:'/'})
this.posts = response.data
})
.catch(e => {
this.errors.push(e)
})
},
onFileChange(e) {
var files = e.target.files || e.dataTransfer.files;
console.log(files);
if (!files.length)
return;
this.createImage(files[0]);
},
createImage(file) {
var image = new Image();
var reader = new FileReader();
// var vm = this;
reader.onload = (e) => {
this.posts.image = e.target.result;
};
reader.readAsDataURL(file);
},
removeImage: function (e) {
this.posts.image = '';
e.posts.target.reset();
}
}
}
</script>
It is expected that the name and the picture will be written into the jamb with categories by the columns name and image, but nothing happens.

Load an observablearray from a URL into a template

I am pretty new to knockoutJS, have completed their interactive tutorials, it was extremely informative.
I read a few posts, like :
KnockoutJS observableArray with template and foreach
It was quite helpful but I couldn't grasp the whole concept as to how to apply it in my context, cause I am fetching data from URL.
One way I thought of solving the problem is maybe by nesting templates.
Cause two things need to be done
Send the observable array to template
Loop over each element and access it's property so as to display in the tmplate
ToDo :
Load the observablearray(), got from a JSON into the template.
The output should be like this :
https://screenshots.firefoxusercontent.com/images/c72ec9d9-075b-40d0-b8cb-f3a4eca76c0d.png
The rendering element
<div class="row">
<div class="col-sm-12">
<div id="template_wallet" data-bind="template: { name: 'wallets_display_tmp', data: coins() }"></div>
### Template
<script type="text/html" id="wallets_display_tmp">
<h2>Wallets<br>
</h2>
<hr />
<table class="table table-striped table-hover">
<thead>
<tr>
<th class="text-center">Currency Name</th>
<th class="text-center">Symbol</th>
<th class="text-center">Amount</th>
<th class="text-center">Deposit/Withdraw</th>
</tr>
</thead>
<tbody>
<tr data-bind="foreach: coin()">
<td class="text-center" data-bind="text: name"></td>
<td class="text-center" data-bind="text: symbol"></td>
<td class=" options">
<div class="center-block text-center">
// <button type="button" class="btn btn-primary btn-xs text-center pop" data-toggle="modal" data-target=".modal" style="margin:-6px 2px" data-purpose="deposit" data-coin=<%= wallet.get('name') %>><span class="fa fa-plus"></span></button>
// <button type="button" class="btn btn-primary btn-xs text-center pop" data-toggle="modal" data-target=".modal" style="margin:-6px 2px" data-purpose="withdrawal" data-coin=<%= wallet.get('name') %> ><span class="fa fa-minus"></span></button>
</div>
</td>
<td></td>
</tr>
</tbody>
</table>
</script>
</div>
</div>
</body>
<script>
$(document).ready(function() {
function walletCoin(){
this.name = ko.observable();
this.symbol = ko.observable();
this.balance = ko.observable();
}
function WalletViewModel(){
var self = this;
self.coins = ko.observableArray([]);
$.getJSON("https://api.myjson.com/bins/13ed0p", function(allData){
console.log(allData);
var mappedCoins = $.map(allData, function(item){
return new walletCoin(item);
});
self.coins(mappedCoins);
});
}
// var walletBalance = new WalletViewModel();
// ko.components.register('', {
// template: {element: 'wallets_display_tmp'},
// });
ko.applyBindings(new WalletViewModel(), document.getElementById("template_wallet"));
});
</script>
The JSON data is
[
{
"name": "Bitcoin",
"symbol": "BTC",
"balance": 0.001212
},
{
"name": "Ripple",
"symbol": "XRP",
"balance": 123.1212
},
{
"name": "Litecoin",
"symbol": "LTC",
"balance": 13.1212
},
{
"name": "Digibyte",
"symbol": "DGB",
"balance": 1231.1212
}
]
Update : I have added a knockoutJS context debugger and added ko.toJSON($data)
Currently I am getting output like this :
$(document).ready(function() {
function walletCoin(){
this.name = ko.observable();
this.symbol = ko.observable();
this.balance = ko.observable();
}
function WalletViewModel(){
var self = this;
self.coins = ko.observableArray([]);
$.getJSON("https://api.myjson.com/bins/13ed0p", function(allData){
console.log(allData);
for (var i = allData.length - 1; i >= 0; i--) {
console.log(allData[i]);
var mappedCoins = ko.mapping.fromJS(allData[i], walletCoin);
self.coins.push(mappedCoins);
}
});
console.log(self.coins());
}
ko.applyBindings(new WalletViewModel(), document.getElementById("template_wallet"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>
<div class="row">
<div class="col-sm-12">
<hr />
<h2>Debug</h2>
<div data-bind="text: ko.toJSON(WalletViewModel)"></div>
<div id="template_wallet" data-bind="template: { name: 'wallets_display_tmp', foreach:coins }"></div>
<script type="text/html" id="wallets_display_tmp">
<h2>Wallets <br>
<small>Estimated Value: 0.00318249 BTC / 47.39 USD</small>
</h2>
<hr />
<table class="table table-striped table-hover">
<thead>
<tr>
<th class="text-center">Currency Name</th>
<th class="text-center">Symbol</th>
<th class="text-center">Amount</th>
<th class="text-center">Deposit/Withdraw</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center" data-bind="text: name"></td>
<td class="text-center" data-bind="text: symbol"></td>
<td class="text-center" data-bind="text: balance"></td>
<td class=" options">
<div class="center-block text-center">
// <button type="button" class="btn btn-primary btn-xs text-center pop" data-toggle="modal" data-target=".modal" style="margin:-6px 2px" data-purpose="deposit" data-coin=<%= wallet.get('name') %>><span class="fa fa-plus"></span></button>
// <button type="button" class="btn btn-primary btn-xs text-center pop" data-toggle="modal" data-target=".modal" style="margin:-6px 2px" data-purpose="withdrawal" data-coin=<%= wallet.get('name') %> ><span class="fa fa-minus"></span></button>
</div>
</td>
</tr>
</tbody>
</table>
</script>
<!-- <div class="container">
<canvas id="live_exchange_chart"></canvas>
</div> -->
</div>
</div>
Do check this :
<script>
$(document).ready(function() {
function walletCoin(){
this.name = ko.observable();
this.symbol = ko.observable();
this.balance = ko.observable();
}
function WalletViewModel(){
var self = this;
self.coins = ko.observableArray([]);
$.getJSON("https://api.myjson.com/bins/13ed0p", function(allData){
console.log(allData);
for (var i = allData.length - 1; i >= 0; i--) {
console.log(allData[i]);
var mappedCoins = ko.mapping.fromJS(allData[i], walletCoin);
self.coins.push(mappedCoins);
}
});
console.log(self.coins());
}
ko.applyBindings(new WalletViewModel(), document.getElementById("template_wallet"));
});
</script>
Here is the jsfiddle for the same.
self.coins = ko.computed(function () {
var coins = {};
self.days = '';
$.ajax({
type: "GET",
dataType: "json",
url: yoururl,
data: {},
async: false,
success: function (response) {
if (response.items) {
for (var i = 0; i < response.items.length; i++) {
coins[i] = {
name: response.items[i].name,
symbol: response.items[i].symbol,
balance: response.items[i].balance
};
}
}
},
error: function () {
console.log('error');
}
});
return coins;
});
I am not fully understand your question, but i guess you need something like this?

Remove Previously selected image in dropzone

I am using dropzone with a form on a modal. I have one button that is 'Add Slider'. When I click on that button the modal is opened. In that modal I have attached an image on dropzone and click on cancel button. When I click on 'Add Slider' button again it shows the previously selected image in dropzone. I want to remove the previously selected image.
Html Code
<modal title="Manage HomeSlider" modaltype="modal-primary" visible="IsFormVisible">
<form name="frmHomeSlider" method="post" class="form-horizontal bv-form" novalidate="novalidate" ng-submit="frmHomeSlider.$valid && fnSaveHomeSlider()">
<modal-body>
<input type="hidden" class="form-control" name="ID" ng-model="HomeSlider.ID" />
<div class="form-group">
<label class="col-lg-3 control-label">Upload Slider Photo</label>
<div class="col-lg-9">
<div class="dropzone profileImage" customdropzone="dropzoneConfig">
<div class="dz-default dz-message">
<div ng-show="HomeSlider.FullPathPhoto==''">
<span>Upload photo here</span>
</div>
<img src="{{HomeSlider.FullPathPhoto}}" required />
</div>
</div>
<input type="hidden" name="Photo" ng-model="HomeSlider.HomeSliderPhoto" required />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Image Name</label>
<div class="col-lg-9">
<input type="text" class="form-control input-sm" name="ImageName" ng-model="HomeSlider.ImageName" placeholder="Enter Image Name" required />
</div>
</div>
</modal-body>
<modal-footer>
<button type="submit" class="btn btn-blue" ng-disabled="frmHomeSlider.$invalid">Submit</button>
<button type="reset" class="btn btn-default" ng-click="fnShowHomeSliderForm(false)">Cancel</button>
</modal-footer>
</form>
</modal>
Js Code
$scope.dropzoneConfig = {
'options': { // passed into the Dropzone constructor
'url': ContentService.UploadHomeSliderPhoto,
'addRemoveLinks': true,
'acceptedFiles': 'image/*',
'uploadMultiple': false,
'maxFiles': 1,
'dictDefaultMessage': 'Upload your photo here',
'init': function () {
this.on('success', function (file, response) {
$scope.HomeSlider.HomeSliderPhoto = response.FileNames[0];
});
this.on('thumbnail', function (file) {
if (file.width < 1800 || file.height < 1200 || file.width > 1800 || file.height > 1200) {
file.rejectDimensions();
}
else {
file.acceptDimensions();
}
});
},
'accept': function (file, done) {
file.acceptDimensions = done;
file.rejectDimensions = function () {
done("The image must be at least 1800 x 1200px");
};
}
},
'eventHandlers': {
'sending': function (file, xhr, formData) {
},
'success': function (file, response) {
$scope.HomeSlider.HomeSliderPhoto = response.FileNames[0];
},
'error': function () {
$rootScope.Common.notifyDanger("Error accure while upload photo.")
}
}
};

Problems understanding inline templates in AngularJS

So im following thinkster.io for an Angular guide and I got stuck on the routing part, specifically, the templating and ui viewing. Heres my code, the problem is, nothing seems to show up anymore :/
var app = angular.module('flapperNews', ['ui.router']);
app.config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl'
});
$urlRouterProvider.otherwise('home')
}]);
app.factory('posts', [function(){
var o = {
posts: [
{title: 'post 1', upvotes: 5},
{title: 'post 2', upvotes: 2},
{title: 'post 3', upvotes: 15},
{title: 'post 4', upvotes: 9},
{title: 'post 5', upvotes: 4}
]
};
return o;
}]);
app.controller('MainCtrl', [
'$scope',
'posts',
function($scope, posts){
$scope.posts = posts.posts;
$scope.addPost = function(){
if(!$scope.title || $scope.title === '') { return; }
$scope.posts.push({title: $scope.title,
upvotes: 0,
link: $scope.link});
$scope.title = "";
$scope.link="";
};
$scope.increaseVotes = function(post) {
post.upvotes += 1;
};
}]);
html>
<head>
<meta charset="UTF-8">
<title>My Angular App!</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.18/angular-ui-router.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js"></script>
<script src="app.js"></script>
<style> .glyphicon-thumbs-up { cursor:pointer } </style>
</head>
<body ng-app="flapperNews">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<ui-view></ui-view>
</div>
</div>
<!--template start-->
<script type="text/ng-template" id="/home.html">
<div class="page-header">
<h1>Flapper News</h1>
</div>
<div data-ng-repeat="post in posts | orderBy: '-upvotes'">
<span ng-click="increaseVotes(post)"><img src="lol.jpeg"></span>
<a ng-show="post.link" href="https://{{post.link}}">
{{post.title}}
</a>
<span ng-hide="post.link">
{{post.title}}
</span>
- upvotes: {{post.upvotes}}
</div>
<form ng-submit="addPost()"
style="margin-top:30px;">
<h3>Add a new post</h3>
<div class="form-group">
<input type="text"
class="form-control"
placeholder="Title"
ng-model="title"></input>
</div>
<div class="form-group">
<input type="text"
class="form-control"
placeholder="Link"
ng-model="link"></input>
</div>
<button type="submit" class="btn btn-primary">Post</button>
</form>
</script>
</body>
</html>
I cant exactly understand whats wrong with it, in my mind ui-view should be rendering the template, yet for some strange reason, it is not. I tried looking in other questions and it seems that doesnt work either.

Angularjs register form not working

I have Angular App, and there is a register form like(Contact-Page with add user) below, but not binding data means (ADD Delete User not working) just displaying the form. Does anyone know how to do it?
View: contact.html
<div class="generic-container" ng-controller="RegCtrl as ctrl">
<div class="panel panel-default">
<div class="panel-heading"><span class="lead">User Registration Form </span></div>
<div class="formcontainer">
<form ng-submit="ctrl.submit()" name="myForm" class="form-horizontal">
<input type="hidden" ng-model="ctrl.user.id" />
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-2 control-lable" for="file">Name</label>
<div class="col-md-7">
<input type="text" ng-model="ctrl.user.username" name="uname" class="username form-control input-sm" placeholder="Enter your name" required ng-minlength="3"/>
<div class="has-error" ng-show="myForm.$dirty">
<span ng-show="myForm.uname.$error.required">This is a required field</span>
<span ng-show="myForm.uname.$error.minlength">Minimum length required is 3</span>
<span ng-show="myForm.uname.$invalid">This field is invalid </span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-2 control-lable" for="file">Address</label>
<div class="col-md-7">
<input type="text" ng-model="ctrl.user.address" class="form-control input-sm" placeholder="Enter your Address. [This field is validation free]"/>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-2 control-lable" for="file">Email</label>
<div class="col-md-7">
<input type="email" ng-model="ctrl.user.email" name="email" class="email form-control input-sm" placeholder="Enter your Email" required/>
<div class="has-error" ng-show="myForm.$dirty">
<span ng-show="myForm.email.$error.required">This is a required field</span>
<span ng-show="myForm.email.$invalid">This field is invalid </span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-actions floatRight">
<input type="submit" value="{{!ctrl.user.id ? 'Add' : 'Update'}}" class="btn btn-primary btn-sm" ng-disabled="myForm.$invalid">
<button type="button" ng-click="ctrl.reset()" class="btn btn-warning btn-sm" ng-disabled="myForm.$pristine">Reset Form</button>
</div>
</div>
</form>
</div>
</div>
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading"><span class="lead">List of Users </span></div>
<div class="tablecontainer">
<table class="table table-hover">
<thead>
<tr>
<th>ID.</th>
<th>Name</th>
<th>Address</th>
<th>Email</th>
<th width="100">
</tr>
</thead>
<tbody>
<tr ng-repeat="u in ctrl.users">
<td><span ng-bind="u.id"></span></td>
<td><span ng-bind="u.username"></span></td>
<td><span ng-bind="u.address"></span></td>
<td><span ng-bind="u.email"></span></td>
<td>
<button type="button" ng-click="ctrl.edit(u.id)" class="btn btn-success custom-width">Edit</button> <button type="button" ng-click="ctrl.remove(u.id)" class="btn btn-danger custom-width">Remove</button>
</tr>
</tbody>
</table>
</div>
</div>
</div>
Contrller:
angular.module('myApp', [])
.controller('AppController', ['$scope', function($scope) {
var self = this;
self.user={id:null,username:'',address:'',email:''};
self.id = 4;
self.users = [// In future posts, we will get it from server using service
{id:1, username: 'Sam', address: 'NY', email: 'sam#abc.com'},
{id:2, username: 'Tomy', address: 'ALBAMA', email: 'tomy#abc.com'},
{id:3, username: 'kelly', address: 'NEBRASKA', email: 'kelly#abc.com'}
];
self.submit = function() {
if(self.user.id==null){
self.user.id = self.id++;
console.log('Saving New User', self.user);
self.users.push(self.user);//Or send to server, we will do it in when handling services
}else{
for(var i = 0; i < self.users.length; i++){
if(self.users[i].id == self.user.id) {
self.users[i] = self.user;
break;
}
}
console.log('User updated with id ', self.user.id);
}
self.reset();
};
self.edit = function(id){
console.log('id to be edited', id);
for(var i = 0; i < self.users.length; i++){
if(self.users[i].id == id) {
self.user = angular.copy(self.users[i]);
break;
}
}
}
self.remove = function(id){
console.log('id to be deleted', id);
for(var i = 0; i < self.users.length; i++){
if(self.users[i].id == id) {
self.users.splice(i,1);
if(self.user.id==id){//It is shown in form, reset it.
self.reset();
}
break;
}
}
}
self.reset = function(){
self.user={id:null,username:'',address:'',email:''};
$scope.myForm.$setPristine(); //reset Form
}
}]);
app.js
'use strict';
/**
* #ngdoc overview
* #name peopleApp
* #description
* # myApp
*
* Main module of the application.
*/
angular
.module('myApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
controllerAs: 'main'
})
.when('/', {
templateUrl: 'views/main.html',
controller: 'CarouselDemoCtrl',
controllerAs: 'main'
})
.when('/Portfolio', {
templateUrl: 'views/Portfolio.html',
controller: 'ctrlApp',
controllerAs: 'Portfolio'
})
.when('/photos', {
templateUrl: 'views/photos.html',
controller: 'AlbumCtrl',
controllerAs: 'photos'
})
.when('/tour', {
templateUrl: 'views/tour.html',
controller: 'ctrlTags',
controllerAs: 'tour'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl',
controllerAs: 'about'
})
.when('/myganesha', {
templateUrl: 'views/myganesha.html',
controller: 'frmController',
controllerAs: 'myganesha'
})
.when('/contact', {
templateUrl: 'views/contact.html',
controller: 'RegCtrl',
controllerAs: 'contact'
})
.when('/login', {
templateUrl: 'views/login.html',
controller: 'loginCtrl',
controllerAs: 'login'
})
.when('/help', {
templateUrl: 'views/help.html',
controller: 'DefaultController',
controllerAs: 'help'
})
.otherwise({
redirectTo: '/'
});
});