Local storage not shown after refresh - javascript

I just can't get it working no matter what I do. Been sitting for hours and nothing. After submitting form I create local storage of values name, surname, email, so that I would be able to use them to fill up form so that user would not have to type them everytime.
submit() is in review.controller.js
(function () {
'use strict';
angular.module('app').controller('ReviewController', ReviewController);
ReviewController.$inject = ['$location', 'AuthenticationService', 'FlashService', 'UniversalService', '$scope', '$sce', '$rootScope','$route','$cookies','localStorageService'];
function ReviewController($location, AuthenticationService, FlashService, UniversalService, $scope, $sce, $rootScope,$route,$cookies,localStorageService) {
var vm = this;
vm.name = null;
vm.surname = null;
vm.Email = null;
vm.review = null;
vm.allgenres = [];
vm.submit = submit;
vm.allreviews = [];
$scope.localArray=[];
loadAllReviews();
submit();
$scope.templates = [{ name: 'man.main.view.html', url: 'main/main.view.html'}];
$scope.template = $scope.templates[0];
function loadAllReviews() {
UniversalService.GetAllReviews()
.then(function (review) {
vm.allreviews = review;
});
}
$scope.init = function () {debugger;
// $scope.$MainController.obtained_array = localStorage.getItem("storageKey");debugger;
$scope.storageKey = localStorage.getItem("storageKey");debugger;
};
$scope.storageKey = localStorage.getItem('storageKey');
/* $scope.$watch("storageKey", function() {debugger;
localStorage.setItem('storageKey', storageKey);
});*/
function submit() {
if($rootScope.name!=null) {
var JSONObject = {
"name":$rootScope.name,
"surname":$rootScope.surname,
"email":$rootScope.email,
"review":$rootScope.review
}
var temp={
"name":$rootScope.name,
"surname":$rootScope.surname,
"email":$rootScope.email
}
$scope.localArray.push(temp);
localStorageService.set("storageKey", $scope.localArray);
$scope.storageKey = localStorageService.get("storageKey");
// $rootScope.obtained_array = localStorageService.get("storageKey"); debugger;
console.log($scope.storageKey);debugger;
var Results = UniversalService.PostReview(JSON.stringify(JSONObject));
}
}
}
main.controller.js
'use strict';
var app= angular.module('app').controller('MainController', MainController);
MainController.$inject = ['$location', 'AuthenticationService', 'FlashService', 'UniversalService', '$scope', '$sce', '$rootScope','$log','PagerService','localStorageService','$mdDialog'];
function MainController($location, AuthenticationService, FlashService, UniversalService, $scope, $sce, $rootScope,$log,PagerService,localStorageService,$mdDialog) {
var vm = this;
vm.allreviews = [];
vm.allusers=[];
vm.allemails=[];
vm.all=[];
vm.avatars=[];
$scope.filteredAll = [];
$scope.all=[];
$scope.items=[];
$scope.pager = {};
$scope.setPage = setPage;
loadAllReviews();
loadAllEmails();
loadAllUsers();
loadAll();
loadAvatars();
initController();
setPage();
submit();
$scope.init = function () {
$scope.$parent.storageKey = localStorage.getItem("storageKey");debugger;
// $scope.obtained_array = localStorage.getItem("storageKey");
// console.log(obtained_array); debugger;
// $scope.storageKey = localStorage.getItem("storageKey");debugger;
};
function refresh() {
location.reload();debugger;
}
function loadAll() {
UniversalService.GetAll()
.then(function (a) {
$scope.all=a;
});
}
function loadAllUsers(callback) {
UniversalService.GetAll()
.then(function (response) {
$scope.users=response;
if (callback) {
callback(response);
}
});
}
function loadAllReviews() {
UniversalService.GetAllReviews()
.then(function (review) {
vm.allreviews = review;
});
}
function loadAllEmails() {
UniversalService.GetAllEmails()
.then(function (email) {
vm.allemails = email;
});
}
function setPage(page) {
loadAllUsers(function (response) {
if (response) {
if (page < 1 || page > $scope.pager.totalPages) {
return;
}
// get pager object from service
$scope.everything=response;
$scope.pager = PagerService.GetPager(response.length, page);
// get current page of items
$scope.items = response.slice($scope.pager.startIndex, $scope.pager.endIndex + 1);
}
});
}
function initController() {
$scope.setPage(1); // initialize to page 1
}
}
HTML file:
<div class="container padding-tb" id="Review">
<div ng-controller="ReviewController" ng-init="init()" ng-app id="Review">
<h2>Add review</h2>
<form name="form" ng-submit="vm.submit()" role="form">
<div >
<div>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="text" ng-model="name" onchange="CallItems()" id="name" class="form-control" ng-model="vm.name" placeholder="Enter name here" required />
<span ng-show="form.name.$dirty && form.name.$error.required" class="help-block">Name is required</span>
</div>
</div>
<div>
<div class="form-group">
<label for="surname">Surname</label>
<input type="text" ng-model="surname" name="text" id="surname" class="form-control" ng-model="vm.surname" placeholder="Enter surname here" required/>
<span ng-show="form.surname.$dirty && form.surname.$error.required" class="help-block">Surname is required</span>
</div>
</div>
<div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" name="email" id="email" class="form-control" ng-model="vm.email" placeholder="Enter email here" required />
<span ng-show="form.email.$dirty && form.email.$error.required" class="help-block">Email is required</span>
</div>
</div>
<div>
<div class="form-group">
<label for="review">Review</label>
<input type="text" name="text" id="review" class="form-control" ng-model="vm.review" placeholder="Enter review here" required/>
<span ng-show="form.review.$dirty && form.review.$error.required" class="help-block">Review is required</span>
</div>
</div>
<div class="form-actions">
<button id="submit" type="submit" onclick="passInfo()" class="btn btn-primary">Submit</button>
<label style="display:none" id="label"><font color="white">Review succesfully created!
<a onclick="refresh()" href="../ang/#!/review">Add new review</a></label> or
View reviews!
</div>
</div>
</form>
<div>
<div ng-init="init()" class="slide-animate-container">
<div class="slide-animate" ng-include="main.view.html"></div>
</div>
</div>
</div>
Currently I add these values to button to test if values are added:
<button ng-disabled="localStorage.getItem('LS_wimmtkey') !== null"> {{obtained_array}}</button>
My main.view is inserted into the review.view (because form and reviews are on the same page, main is for the review listing and reviews are submitted form)
After submiting form all these values appear in the button, but after refreshing page none of them are shown anymore. I kind of understand that it is all because everything I do with local storage is inside submit() function, but I am not sure how to fix it

You can write a init function on second controller and set the local Storage value in a variable.So whenever you refresh the page, init function will be called and local storage value will be available for you to use it in View

see below line:
<button ng-disabled="localStorage.getItem('LS_wimmtkey') !== null"> {{obtained_array}}</button>
"obtained_array" belong to $rootScope, so $rootScope can't bind to the template(binding to $rootScope is not possible )
quick solution is: change the following line
in case of: MainController
$scope.obtained_array = localStorage.getItem("LS_wimmtkey");debugger;
in case of :ReviewController (you are setting in this ctrl "LS_wimmtkey")
$scope.$parent.obtained_array = localStorage.getItem("LS_wimmtkey");debugger;

Related

Newer versions of both AngularJS and Firebase, yet I am still getting TypeError: $cookies.get is not a function

(function() {
function uCtrl($uibModalInstance, $cookies) {
var saveUser = function(username) {
$cookies.put('blocChatCurrentUser', 'username');
};
var getUser = function() {
return $cookies.get('blocChatCurrentUser');
};
this.isValid = function() {
var currentUser = getUser();
if(!currentUser === undefined) {
currentUser = currentUser.replace(/^\s+/, '').replace(/\s+$/, '');
}
else if(currentUser === '' || currentUser === undefined) {
this.currentUserError = 'Username Cannot Be Empty';
this.currentUserErrorTrue = true;
this.setUsername.name = '';
return;
}
else {
$cookies.blocChatCurrentUser = currentUser;
saveUser(currentUser);
$uibModalInstance.dismiss();
}
};
}
angular
.module('blocChat')
.controller('uCtrl', ['$cookies', '$uibModalInstance', uCtrl]);
})();
<div>
<div class = "modal-header">
<h2 class = "modal-title">Set A Username</h2>
</div>
<div class = "modal-body">
<br>This name will appear when you send messages.</br>
<form name = "Username" ng-submit = "cookieThis.isValid()">
<div class = "input-group animated">
<input type = "text" class = "form-control finderBar" ng-model = "this.username" name = "username" ng-minlength = "1" required autofocus>
</div>
</form>
</div>
<div class = "modal-footer">
<button class="btn btn-primary" type="button" ng-click= "cookieThis.isValid()" ng-disabled = "this.username == null">Set Username</button>
</div>
</div>
All the other files work perfectly fine. ModalInstanceCtrl and ModalCtrl all have been tested with respective .html files and they work. So basically, I am trying to take the user provided username and store it in a cookie. Of course, there are getUser() and setUser() method for using the cookie.

ng-disabled nor enabling Submit button

I hope you can help me.
I think I am missing something, and just can't figure it out. For some reason I cannot get ng-disabled="formSubmmision" to enable the button when the form has been filled in.
Any help will be greatly appreciated!
I have the following view and controller:
Here is my view:
<section class="mainbar" data-ng-controller="adminVendorNumberController as vm">
<article class="booty">
<div class="row-fluid">
<div class="col-md-12">
<h1 class="main-heading"><strong>Vendor Number Admin</strong></h1>
</div>
</div>
<form name="formInsertVendorNumber" novalidate>
<div class="row-fluid island">
<div class="col-md-12">
<div>
<!--Here-->
<div class="header">
<div class="green"><span class="icon-user-tie"></span></div>
<h2 class="title">Add New <strong>Vendor Number</strong></h2>
</div>
<div class="row-fluid">
<!-- Customer-->
<div class="col-md-4">
<label>Vendor</label>
<div class="input-dropdown">
<cc-dropdown cc-placeholder="Select Vendor"
ng-model="NewVendorNumber.Vendor"
ng-disabled="false"
ng-options="vendorData"
cc-fields="VendorDescription"
cc-key-field="VendorId"
cc-allow-search="false"
ng-required="false"
ng-change="vendorSelected()"
name="iVendor">
</cc-dropdown>
</div>
</div>
<!-- End Customer-->
<!--Region -->
<!-- Update: ng-disabled="NewVendorNumber.Vendor == null" -->
<div class="col-md-4">
<label>Item Group</label>
<div class="input-dropdown">
<cc-dropdown cc-placeholder="Select Item Group"
ng-model="NewVendorNumber.ItemGroup"
ng-disabled="NewVendorNumber.Vendor == null"
ng-options="itemGroupData"
cc-fields="ItemGroupDescription"
cc-key-field="ItemGroupId"
cc-allow-search="false"
ng-required="false"
ng-change="itemGroupSelected()"
name="iItemGroup">
</cc-dropdown>
</div>
</div>
<!--End Region -->
<div class="col-md-4">
<label>Vendor Item Number</label>
<div class="input-text">
<input type="text" name="iVendorItemNumber" required ng-model="NewVendorNumber.ItemNumber" />
<div class="errorIcon fadeInOut" ng-class="{error : VendorItemError}" ng-mouseenter="VendorItemError = true" ng-mouseleave="VendorItemError = false"
ng-show="(formInsertVendorNumber.$submitted || formInsertVendorNumber.iVendorItemNumber.$touched) && formInsertVendorNumber.iVendorItemNumber.$error.required">
<span class="icon-warning"></span>
<div>
<p>
<span>Please enter a Vendor Item Number</span>
</p>
</div>
</div>
</div>
</div>
<div class="col-md-8">
<label>Vendor Item Description</label>
<div class="input-text">
<input type="text" name="iVendorItemDescription" required ng-model="NewVendorNumber.ItemDescription" />
<div class="errorIcon fadeInOut" ng-class="{error : VendorItemDescriptionError}" ng-mouseenter="VendorItemDescriptionError = true" ng-mouseleave="VendorItemDescriptionError = false"
ng-show="(formInsertVendorNumber.$submitted || formInsertVendorNumber.iVendorItemDescription.$touched) && formInsertVendorNumber.iVendorItemDescription.$error.required">
<span class="icon-warning"></span>
<div>
<p>
<span>Please enter a Vendor Item Description</span>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="separator"></div>
<div class="footer">
<!-- Update: ng-disabled="formSubmmision" -->
<button type="submit" class="btn btn-default right" ng-click="save()" ng-disabled="formSubmmision"><span class="icon-checkmark"> </span>Save</button>
</div>
</div>
</div>
</div>
</form>
</article>
</section>
Here is my controller:
(function () {
"use strict";
angular
.module('app.adminVendorNumber')
.controller('adminVendorNumberController', adminVendorNumberController);
adminVendorNumberController.$inject = ['$http', 'logger', '$scope'];
function adminVendorNumberController($http, logger, $scope) {
var vm = $scope;
vm.formSubmmision = true;
vm.vendorItemData = null;
vm.itemGroupData = null;
vm.vendorData = null;
vm.vendorSelected = vendorSelected;
vm.itemGroupSelected = itemGroupSelected;
vm.save = save;
activate();
function activate() {
return vendorItemData().then(getAllItemGroups).then(getVendorData).then(function () {
logger.info('Activated Vendor Number Creation');
});
}
function vendorItemData(data) {
return $http.get('/api/vendorItem/getAll/')
.then(Success)
.catch(Failure);
function Success(responce) {
vm.vendorItemData = responce.data.Records;
return vm.vendorItemData;
}
function Failure(error) {
logger.error('Failed to Get Customer Data ' + error.data.Message);
}
}
function getVendorData(data) {
return $http.get('/api/vendor/GetAllVendors/')
.then(Success)
.catch(Failure);
function Success(responce) {
vm.vendorData = responce.data.Records;
return vm.vendorData;
}
function Failure(error) {
logger.error('Failed to Get Vendor Data ' + error.data.Message);
}
}
function getAllItemGroups(data) {
return $http.get('/api/itemGroup/GetAllItemGroups/')
.then(Success)
.catch(Failure);
function Success(response) {
vm.itemGroupData = response.data.Records;
return vm.itemGroupData;
}
function Failure(error) {
logger.error('Failed to Get Item Group Data ' + error.data.Message);
}
}
// Form Selections
function itemGroupSelected() {
vm.formSubmmision = true;
return getItemGroupById(vm.NewVendorNumber.ItemGroup.ItemGroupId);
}
function getItemGroupById(itemGroupId) {
return $http.get("/api/itemGroup/GetItemGroupById/?itemGroupId=" + itemGroupId)
.then(Success)
.catch(Failure);
function Success(responce) {
vm.itemGroupSelected = responce.data.Records;
return vm.itemGroupSelected, responce.data;
}
function Failure(error) {
logger.error('Failed to get Vendor Data ' + error.data.Message);
}
}
function vendorSelected() {
vm.formSubmmision = true;
return getVendorById(vm.NewVendorNumber.Vendor.VendorId);
}
function getVendorById(vendorId) {
return $http.get("/api/vendor/ReadVendor/?vendorid=" + vendorId)
.then(Success)
.catch(Failure);
function Success(responce) {
vm.vendorSelected = responce.data.Records;
return vm.vendorSelected, responce.data;
}
function Failure(error) {
logger.error('Failed to get Vendor Data ' + error.data.Message);
}
}
// Save
function save() {
if (vm.formInsertVendorNumber.$valid) {
postNewData();
}
else {
logger.error('Error: Validation failed. Please correct data and try again');
vm.formSubmmision = false;
}
}
function postNewData() {
//prepare data
var data = {
VendorItemId: 0,
ItemNumber: vm.NewVendorNumber.ItemNumber,
ItemDescription: vm.NewVendorNumber.ItemDescription,
ItemType: "",
OnCall: "",
Vendor: {
VendorId: vm.NewVendorNumber.Vendor.VendorId,
VendorDescription: vm.NewVendorNumber.Vendor.VendorDescription,
Active: vm.NewVendorNumber.Vendor.Active,
Id: vm.NewVendorNumber.Vendor.Id,
ChangedDate: vm.NewVendorNumber.Vendor.ChangedDate
},
ItemGroup: {
ItemGroupId: vm.NewVendorNumber.ItemGroup.ItemGroupId,
ItemGroupDescription: vm.NewVendorNumber.ItemGroup.ItemGroupDescription,
Id: vm.NewVendorNumber.ItemGroup.Id,
ItemCodeGroup: vm.NewVendorNumber.ItemGroup.ItemCodeGroup
}
}
$http.post('/api/vendorItem/PostVendorItem/', data)
.then(postDataComplete)
.catch(getDataFailed);
function postDataComplete(response) {
logger.info("Vendor Item Number Created ");
vm.NewVendorNumber = null;
vm.formSubmmision = true;
vm.formInsertVendorNumber.$setPristine();
vm.formInsertVendorNumber.$setUntouched();
return vm.NewVendorNumber;
}
function getDataFailed(error) {
logger.error('Failed to Vendor Item Number ' + error.data.Message);
return;
}
}
};
}
)();
you are using CONTROLLER AS syntax.
Your controller should be ...
var vm = this;
NOT ...
var vm = $scope;
also you should be using ...
formInsertVendorNumber.$valid to disable or enable the submit button.
you should, inside your form, display ...
<span>{{ formInsertVendorNumber }}</span>
This will output a lot of angular variables associated with the form. You should see that formInsertVendorNumber.$valid is true when the form is valid and false when it is not. use that to toggle your button.
I solved my problem by adding another simple function called formSubmit() to my controller:
function getItemGroupById(itemGroupId) {
return $http.get("/api/itemGroup/GetItemGroupById/?itemGroupId=" + itemGroupId)
.then(Success)
.then(formSubmit)
.catch(Failure);
function Success(responce) {
vm.itemGroupSelected = responce.data.Records;
return vm.itemGroupSelected, responce.data;
}
function Failure(error) {
logger.error('Failed to get Vendor Data ' + error.data.Message);
}
}
function formSubmit() {
vm.formSubmmision = false;
return vm.formSubmmision;
}

Show only clicked element values from multiple ng-click events angularjs

i have 10 more ng-click events, but i want to show only clicked element value where i have to change, but i updated in code there was so many true or false duplicates i have to write, pls help me that have to show only clicked ng-show values without using 'true or false' booleen functions in each click event.
var app = angular.module('myapp', ['ngSanitize']);
app.controller('AddCtrl', function ($scope, $compile) {
$scope.field = {single: 'untitled',single2:'default',single3:'enter'};
$scope.addName1 = function (index) {
var name1html = '<fieldset id="name1" ng-click="selectName1($index)"><label ng-bind-html="field.single"></label><input type="text" placeholder="Enter name"><button ng-click="removeName1($index)">-</button></fieldset>';
var name1 = $compile(name1html)($scope);
angular.element(document.getElementById('drop')).append(name1);
};
$scope.removeName1 = function (index) {
var myEl = angular.element(document.querySelector('#name1'));
myEl.remove();
};
$scope.selectName1 = function (index) {
$scope.showName1 = true;
$scope.showName2 = false;
$scope.showName3 = false;
};
$scope.addName2 = function (index) {
var name2html = '<fieldset id="name2" ng-click="selectName2($index)"><label ng-bind-html="field.single2"></label><input type="text" placeholder="Enter name"><button ng-click="removeName2($index)">-</button></fieldset>';
var name2 = $compile(name2html)($scope);
angular.element(document.getElementById('drop')).append(name2);
};
$scope.removeName2 = function (index) {
var myEl = angular.element(document.querySelector('#name2'));
myEl.remove();
};
$scope.selectName2 = function (index) {
$scope.showName2 = true;
$scope.showName1 = false;
$scope.showName3 = false;
};
$scope.addName3 = function (index) {
var name3html = '<fieldset id="name3" ng-click="selectName3($index)"><label ng-bind-html="field.single3"></label><input type="text" placeholder="Enter name"><button ng-click="removeName3($index)">-</button></fieldset>';
var name3 = $compile(name3html)($scope);
angular.element(document.getElementById('drop')).append(name3);
};
$scope.removeName3 = function (index) {
var myEl = angular.element(document.querySelector('#name3'));
myEl.remove();
};
$scope.selectName3 = function (index) {
$scope.showName3 = true;
$scope.showName1 = false;
$scope.showName2 = false;
};
});
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular.min.js"></script>
<script src="https://code.angularjs.org/1.5.0-rc.0/angular-sanitize.min.js"></script>
</head>
<body ng-controller="AddCtrl">
<div id="drop"></div>
<button ng-click="addName1($index)">Name1</button>
<button ng-click="addName2($index)">Name2</button>
<button ng-click="addName3($index)">Name3</button>
<form ng-show="showName1">
<div class="form-group">
<label>Field Label(?)</label>
<br/>
<input ng-model="field.single">
</div>
</form>
<form ng-show="showName2">
<div class="form-group">
<label>Field Label(?)</label>
<br/>
<input ng-model="field.single2">
</div>
</form>
<form ng-show="showName3">
<div class="form-group">
<label>Field Label(?)</label>
<br/>
<input ng-model="field.single3">
</div>
</form>
</body>
</html>
here is plunkr http://plnkr.co/edit/oFytWlQMIaCaeakHNk71?p=preview
You will need "ng-repeat" in the HTML. Set an Array on $scope and let the template determine what HTML elements to add. Typically, $index is only set by ng-repeat.
Read more here: https://docs.angularjs.org/api/ng/directive/ngRepeat

AngularJS : interactive search

I'm new to AngularJS, and, for a project, I need to make an interactive search engine.
So I did this for now :
article/views/articles.html
<form class="form-inline">
<div class="form-group">
<label for="filter-text">Text </label>
<input type="search" class="form-control" id="filter-text" placeholder="Search for text" ng-change="applyFilter();" ng-model="filters.text">
</div>
<div class="form-group">
<label for="filter-date-start">Entre </label>
<input type="date" class="form-control" id="filter-date-start" placeholder="Entre" ng-change="applyFilter();" ng-model="filters.date_start">
</div>
<div class="form-group">
<label for="filter-date-end">Et </label>
<input type="date" class="form-control" id="filter-date-end" placeholder="Et" ng-change="applyFilter();" ng-model="filters.date_end">
</div>
</form>
<div class="hidden-sm hidden-xs col-md-6">
<div
ng-repeat="article in articles"
class="article"
ng-include="'article/views/article.html'" >
</div>
</div>
article/views/article.html
<div ng-hide="article.isHidden">
<!-- My Article DOM -->
</div>
article/article.js
angular
.factory('articleRetriever', function ($http, $q){
this.getLast = function( id ){
var url = 'http://localhost:8080/articles/';
if (id) url += id;
return $http.get(url ,{'Access-Control-Allow-Origin': 'localhost:*'})
.then(function(response) {
var articles = [];
for (var idx in response.data.data) {
var article = response.data.data[idx];
article.isHidden = false;
articles.push(article);
}
return articles;
});
};
return this;
})
.controller('ArticlesCtrl', ['$scope', 'articleRetriever', function($scope, articleRetriever) {
$scope.articles = [];
$scope.filters = { tag: null, date_start : null, date_end : null, text : null };
articleRetriever.getLast()
.then(function(arrItems){
$scope.articlesLoaded = arrItems;
$scope.articles = $scope.articles.concat(arrItems);
});
$scope.applyFilter = function () {
var contains = $scope.filters.text.split(' ');
for (var idx in $scope.articles) {;
$scope.articles[idx].isHidden = true;
if (contains.length > 0) {
for( var jdx in contains) {
if ($scope.articles[idx].body.toUpperCase().indexOf( contains[jdx] ) > -1)
$scope.articles[idx].isHidden = false;
if ($scope.articles[idx].title.toUpperCase().indexOf( contains[jdx] ) > -1)
$scope.articles[idx].isHidden = false;
}
}
}
};
});
But when I fill the input with some text, the modification on $scope.articles didn't hide the article's div in article/views/article.html.
Can someone explain why and could give me a solution ?
Thanks :-)
My bad, the search form wasn't inside the div with the ng-controller="ArticleCtrl" directive, I moved it inside and all works perfectly now.

push increment item into an array in Angularjs

http://plnkr.co/edit/NDTgTaTO1xT7bLS1FALN?p=preview
<button ng-click="addRow()">add row</button>
<div ng-repeat="row in rows">
<input type="text" placeholder="name"><input type="tel" placeholder="tel">
</div>
I want to push new row and save all the fields but now I'm stuck at adding new rows. How to know the current number of row and do increment to push into the array?
Look at this example I created which allows you to generate up to eight unique input fields for Telephone and Text Entries.
var app = angular.module("MyApp", []);
app.controller("MyCtrl", function($scope) {
$scope.rows = [];
var Row = function(tel, text) {
// Private data
var private = {
tel: tel,
text: text
}
// Expose public API
return {
get: function( prop ) {
if ( private.hasOwnProperty( prop ) ) {
return private[ prop ];
}
}
}
};
$scope.addRow = function(){
if($scope.rows.length < 8){
var newItemNum = $scope.rows.length + 1;
var row = new Row('item' + newItemNum, 'item' + newItemNum);
$scope.rows.push(row);
}
};
$scope.saveAll = function(){
// $scope.result = 'something';
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp">
<div ng-controller="MyCtrl">
<h2>Setting</h2>
<button ng-click="addRow()">Add Row</button>
<br />
<div ng-repeat="row in rows">
<input type="text" placeholder="Text" ng-model="row.textModel" >
<input type="tel" placeholder="Phone" ng-model="row.telModel" >
</div>
<br />
{{rows}}
</div>
</div>
Move functions inside controller 'Ctrl'.
In your script:
function Ctrl($scope) {
$scope.result = "something";
$scope.rows = ['1'];
$scope.addRow = function(){
if ($scope.rows.length < 8) {
$scope.rows.push($scope.rows.length + 1);
}
}
$scope.saveAll = function(){
// $scope.result = 'something';
}
}

Categories

Resources