Custom service to display array in angularjs - javascript

Can anyone please explain to me how to create a custom service for displaying the array .the array is created inside the service and a function savedata() which saves the objects in the array.like wise another function i want to create which will display the array. thanks in advance
<!DOCTYPE html>
<html ng-app="noteApp">
<head>
<title>Note App</title>
<script src="angular.js"></script>
</head>
<body>
<div ng-controller="noteCtrl">
<form name="noteForm">
NoteId: <input type="number" name="id" ng-model="note.id" required>
NoteTitle: <input type="text" name="title" ng-model="note.title" required>
NoteDiscription: <input type="text" name="discription" ng-model="note.discription" required><br><br>
<button ng-click="add()" ng-disabled="noteForm.$invalid">Click</button>
</form>
<div ng-repeat="number in noteArray track by $index">
<h3>{{::number.id}}</h3>
<h3>{{::number.title}}</h3>
<h3 >{{::number.discription}}</h3>
</div>
</div>
<script>
var app=angular.module('noteApp',[]);
app.service('dataService',function(){
var noteArray=[];
this.saveData=function(data){
console.log(noteArray);
return noteArray.push(data);
}
this.displayData=function(){
//return zz;
}
});
app.controller('noteCtrl',function($scope,dataService) {
$scope.add=function(){
dataService.saveData($scope.note);
//dataService.displayData();
}
});
</script>
</body>
</html>

You are on the right track, just return the array inside the displayData()
this.displayData=function(){
return noteArray;
}
DEMO
var app=angular.module('noteApp',[]);
app.service('dataService',function(){
var noteArray=[];
this.saveData=function(data){
console.log(noteArray);
return noteArray.push(data);
}
this.displayData=function(){
return noteArray;
}
});
app.controller('noteCtrl',function($scope,dataService) {
$scope.noteArray=[];
$scope.add=function(){
dataService.saveData($scope.note);
$scope.noteArray = dataService.displayData();
}
});
<html ng-app="noteApp">
<head>
<title>Note App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body>
<div ng-controller="noteCtrl">
<form name="noteForm">
NoteId: <input type="number" name="id" ng-model="note.id" required><br><br>
NoteTitle: <input type="text" name="title" ng-model="note.title" required>
<br><br>
NoteDiscription: <input type="text" name="discription" ng-
model="note.discription" required><br><br>
<button ng-click="add()" >Click</button>
</form>
<div ng-repeat="number in noteArray track by $index">
<h3 >{{number.id}}</h3>
<h3 >{{number.title}}</h3>
<h3 >{{number.discription}}</h3>
</div>
</div>
</body>
</html>

Well I think that you need some like that:
'use strict';
app.factory('$shared',[function(){
function foo() {
var self = this;
self.list = [];
}
return new foo();
}]);
app.controller('mainCtrl', ['$scope', '$shared', function($scope, $shared){
$scope.shared = $shared;
//... many things here
$scope.onClick = function() {
// be sure that, I use "shared" from $scope, no directly like "$shared"
$scope.shared.list.push("val1");
console.log("my shared array:", $scope.shared.list);
}
}]);
app.controller('secondCtrl', ['$scope', '$shared', function($scope, $shared){
$scope.shared = $shared;
//... many things here
$scope.onKeyPress = function() {
// be sure that, I use "shared" from $scope, no directly like "$shared"
$scope.shared.list.push("val2");
console.log("my shared array:", $scope.shared.list);
}
}]);

Related

Angularjs dynamic form contents

Here is my angular view,
<label class="control-label">skipColumns:</label>
<br />
<fieldset ng-repeat="skipColumn in config.skipColumns track by $index">
<input type="text" class="form-control" ng-model="skipColumn[0]" /><br />
</fieldset>
<button class="btn btn-default" ng-click="addNewSkipColumn(skipColumn)">Add SkipColumn</button>
<br />
which adds new textfield every time i click addSkipColumn button.
here is my js code:
$scope.config.skipColumns = [];
$scope.addNewSkipColumn = function (skipColumn) {
if($scope.config.skipColumns==null){
$scope.config.skipColumns=[];
}
$scope.config.skipColumns.push([]);
}
so the problem is when I display or see the structure of $scope.config.skipColumns, It gives the following output:
{
skipColumns:[["content of textfield1"],["content of textfield1"]..]
}
But what I need is,`
{
skipColumns:["content of textfield1","content of textfield1",..]
}
please help me.("content of textfield" resfers to form data)
What you need here is to change what you are pushing in config.skipColumns array. Like this:
$scope.addNewSkipColumn = function(skipColumn) {
$scope.config.skipColumns.push("");
}
And, ng-repeat would be like:
<fieldset ng-repeat="skipColumn in config.skipColumns track by $index">
<input type="text" ng-model="config.skipColumns[$index]" />
</fieldset>
(why did I not use skipColumn directly in the ng-model?)
Here's working example:
angular.module("myApp", [])
.controller("ctrl", function($scope) {
$scope.config = {};
$scope.config.skipColumns = [];
$scope.addNewSkipColumn = function(skipColumn) {
$scope.config.skipColumns.push("");
}
})
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="myApp" ng-controller="ctrl">
<label class="control-label">skipColumns:</label>
<br />
<fieldset ng-repeat="skipColumn in config.skipColumns track by $index">
<input type="text" class="form-control" ng-model="config.skipColumns[$index]" />
</fieldset>
<button class="btn btn-default" ng-click="addNewSkipColumn()">Add SkipColumn</button>
<br />
<br>
<pre>{{config.skipColumns}}</pre>
</body>
</html>
See this... Just push value instead of array.
var app = angular.module('angularjs', []);
app.controller('MainCtrl', function($scope) {
$scope.choices = ['choice1'];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push('choice'+newItemNo);
};
$scope.removeChoice = function() {
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div ng-app="angularjs" ng-controller="MainCtrl">
<fieldset data-ng-repeat="choice in choices">
<select>
<option>Mobile</option>
<option>Office</option>
<option>Home</option>
</select>
<input type="text" ng-model="choice.name" name="" placeholder="Enter mobile number">
<button class="remove" ng-show="$last" ng-click="removeChoice()">-</button>
</fieldset>
<button class="addfields" ng-click="addNewChoice()">Add fields</button>
<div id="choicesDisplay">
{{ choices }}
</div>
</div>

ng-controller Angular capitalize input

I want the first typed letter turn into a capital letter, but struggeling with Angular. Maybe it is a little detail that I missed out, so a fresh eye to look at this would be helpful.
var app = angular.module("todoApp", []);
app.filter("NameInput", function(){
return function(input, scope){
if (input!=null)
input = input.toLowerCase();
return input.substring(0,1).toUpperCase()+input.substring(1);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<body ng-app="todoApp" ng-cloak>
<div id="wrapper">
<div ng-controller="NameInput">
<label>Name:</label>
<input id="name-input" type="text" ng-model="yourName" placeholder="Enter a name here">
<hr>
<h1>Hello {{yourName}}</h1>
</div>
</div>
</body>
Here you go...
I think this might help you
var app = angular.module("todoApp", []);
app.filter("NameInput", function() {
return function(input) {
if (input != null) {
input = input.toLowerCase();
return input.substring(0, 1).toUpperCase() + input.substring(1);
}
}
})
.controller('NameInput', function($scope) {
$scope.yourName = "";
});
<body ng-app="todoApp" ng-cloak>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.js"></script>
<div id="wrapper">
<div ng-controller="NameInput">
<label>Name:</label>
<input id="name-input" type="text" ng-model="yourName" placeholder="Enter a name here">
<hr>
<h1>Hello {{yourName | NameInput}}</h1>
</div>
</div>
</body>

Angular JS - nesting templates (double curly brackets {{}} )

Is there a way to nest angular templates?
for example having the following variables:
$scope.myVar = 'hello {{name}}, you weigh {{weight}}'
$scope.name = '';
$scope.weight = '';
And having the html file looking something like:
<h1>{{myVar}}</h1>
<div>
Your Name:
<input ng-model="name" type="text">
</div>
<div>
Your Weight:
<input ng-model="weight" type="text">
</div>
And then have angular dynamically setting the name and weight template from myVar?
I think that you are looking for is meaningless. You could define a function like below and then call this function in the header.
$scope.myVar = function() {
return 'hello ' + $scope.name + ' you weigh '+ $scope.weight;
}
var app = angular.module('app',[]);
app.controller('mainController',['$scope', function($scope){
$scope.name = "test";
$scope.weight = 100;
$scope.myVar = function() { return 'hello ' + $scope.name + ' you weigh ' + $scope.weight; };
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html>
<head>
</head>
<body ng-app="app">
<div ng-controller="mainController">
<h1>{{myVar()}}</h1>
<div>
Your Name:
<input ng-model="name" type="text"/>
</div>
<br/>
<div>
Your Weight:
<input ng-model="weight" type="text"/>
</div>
</div>
</body>
</html>
I ended up realizing that I had scoping errors. So, to solve the binding errors, I used $interpolate. See: How to evaluate angularjs expression inside another expression
Sure you would just do:
<h1>Hello {{name}} you weigh {{weight}}</h1>
<div>
Your Name:
<input ng-model="name" type="text">
</div>
<div>
Your Weight:
<input ng-model="weight" type="text">
</div>

Angularjs checkbox checked enables input field

I'm kinda new in AngularJS and my issue is:
I have a loop like this:
<body ng-app="ngToggle">
<div ng-controller="AppCtrl">
<input type="checkbox" ng-repeat="btn in btns" class="here" value="{{btn.value}}">
<input type="text" class="uncheck" disabled>
</div>
</body>
One of those checkboxes has a value of "OTHER", and what I need to do is: when the checkbox with the "OTHER" value is checked it remove the disabled attribute from the <input type="text" class="uncheck" disabled>
This is my controller:
angular.module('ngToggle', [])
.controller('AppCtrl',['$scope', function($scope){
$scope.btns = [
{value:'one'},
{value:'two'},
{value:'other'}
];
}]);
Hope someone can help me,
Thanks.
Use ng-change directive and test value of other checkbox in forEach-loop
angular.module('ngToggle', [])
.controller('AppCtrl', ['$scope',
function($scope) {
$scope.disabled = true;
$scope.btns = [{
value: 'one'
}, {
value: 'two'
}, {
value: 'other'
}];
$scope.onChange = function() {
$scope.btns.forEach(function(btn) {
if (btn.value === 'other' && btn.status === true) {
$scope.disabled = false;
} else {
$scope.disabled = true;
}
});
}
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="ngToggle">
<div ng-controller="AppCtrl">
<input type="checkbox" ng-repeat="btn in btns" class="here" ng-model='btn.status' ng-change='onChange()'>
<input type="text" class="uncheck" ng-disabled='disabled'>
</div>
</body>
try like this.
angular.module('ngToggle', [])
.controller('AppCtrl',['$scope', function($scope){
$scope.btns = [
{value:'one',name:"one"},
{value:'two',name:'two'},
{value:'other',name:'other'}
];
$scope.disable=true;
$scope.check = function(value){
if(value == "'other'")
$scope.disable = false;
else
$scope.disable=true;
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ngToggle">
<div ng-controller="AppCtrl">
<div ng-repeat="btn in btns">
<input type="checkbox" ng-model="btn.value" ng-true-value="'{{btn.value}}'" ng-change="check(btn.value)" >{{btn.name}}
</div>
<input type="text" class="uncheck" ng-disabled='disable'>
</div>
</div>
Make use of ng-models. Please avoild using "values attribute" as well in AngularJS. The alternative for values is "ng-init". Well anyway, here is a working code:
<!DOCTYPE html>
<html >
<head>
<link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
</head>
<body ng-app="ngToggle">
<div ng-controller="AppCtrl">
<p ng-repeat="btn in btns">
<input type="checkbox" ng-model="btn.bool" value="ss" class="here" > {{ btn.value }}
</p>
<input type="text" ng-model="textModel" class="uncheck" ng-disabled="other.bool">
<p>{{ other.bool }} -- {{textModel }}</p>
</div>
<script type="text/javascript">
angular.module('ngToggle', [])
.controller('AppCtrl',['$scope', function($scope){
$scope.btns = [
{value:'one', bool:false},
{value:'two', bool:true},
{value:'other', bool:true}
];
$scope.otherBool = $scope.btns[2]['bool'];
$scope.btns.map(function(obj){
//alert(JSON.stringify(obj))
if((obj.value) == 'other'){
$scope.other = obj;
}
});
}]);
</script>
</body>
</html>
YOu can check it in plunker as well: http://plnkr.co/edit/GODfWbhlWvzjLKHFcEYs?p=preview

Filling data in form using angular

I am a true beginner at Angular (but not JS), started yesterday, so I hope you forgive me if this question sound stupid. Consider the following small application:
HTML:
<!doctype html>
<html ng-app="todoApp">
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="/js/TestController.js"></script>
</head>
<body ng-controller="TestController as myControl">
<div id="overlaybox">
<button ng-click="myControl.showUpd(4)">Test</button><br/><br/><br/>
<form ng-submit="myControl.updTodo()">
Note:<br/>
<textarea rows="5" cols="30" id="updContent" ng-model="noteupd.content"></textarea><br/>
Deadline (format YYYY-MM-DD HH:MM):<br/>
<input type="text" id="updDeadline" ng-model="noteupd.deadline" /><br/>
Completed:
<input type="checkbox" id="updCompleted" ng-model="noteupd.completed" /><br/>
<input type="hidden" id="updID" ng-model="noteupd.id" /><br/>
<input type="submit" value="Update" />
</form>
</div>
</body>
</html>
Angular-controller:
angular.module('todoApp', []).controller('TestController', function($scope, $http) {
var thisApp = this;
thisApp.showUpd = function(noteID) {
$http({method : 'GET', url : 'http://localhost:8000/notes/' + noteID})
.then (function(response) {
console.log(response.data.content);
console.log(response.data.deadline);
console.log(response.data.id);
console.log(response.data.completed);
document.getElementById("updContent").innerHTML = response.data.content;
document.getElementById("updDeadline").value = response.data.deadline;
document.getElementById("updID").value = response.data.id;
if (response.data.completed == 1) {
document.getElementById("updCompleted").checked = true;
} else {
document.getElementById("updCompleted").checked = false;
}
}, function() {
alert("Error getting todo note");
});
}
thisApp.updTodo = function(noteupd) {
console.log("TEST");
console.log($scope.noteupd);
}
});
After clicking Test-button I get the following output in my console:
TestController.js:7 123123
TestController.js:8 2016-01-05 10:28:42
TestController.js:9 4
TestController.js:10 0
By then, the fields in the form have been filled in (and the hidden field has a value). And after clicking Update I get this in the console:
TestController.js:27 TEST
TestController.js:28 undefined
If i change the values in the fields manually, I do get something else instead of "undefined", but the idea is that one should not have to change the values. Also, the object does not contain the hidden "id" even if all fields are changed.
Obviously, I'm a beginner at this, and obviously I'm doing it wrong, but do anyone have a suggestion on how I can make this work?
Your html is fine but your code needs fixing
First define noteupd in your code
Use noteupd to change your html values rather then document.getElementById
That should fix your code it will end up looking like this
angular.module('todoApp', []).controller('TestController', function($scope, $http) {
var thisApp = this;
$scope.noteupd={}; //defining noteupd
var noteupd=$scope.noteupd; //preventing scope issues
thisApp.showUpd = function(noteID) {
$http({method : 'GET', url : 'http://localhost:8000/notes/' + noteID})
.then (function(response) {
console.log(response.data.content);
console.log(response.data.deadline);
console.log(response.data.id);
console.log(response.data.completed);
//updating your html
noteupd.content= response.data.content;
noteupd.deadline = response.data.deadline;
noteupd.id= response.data.id;
if (response.data.completed == 1) {
noteupd.completed = true;
} else {
noteupd.completed = false;
}
}, function() {
alert("Error getting todo note");
});
}
thisApp.updTodo = function(noteupd) {
console.log("TEST");
console.log($scope.noteupd);
}
});
If you are using this variable against $scope .. you have always ng-controller with alias , and you can only access properties or methods of controller with controller alias only ..
if you didnt use ng-controller= "TestController as myController"
and not access methods as myController.method() .. your example won't be worked...(section 2)
Here is some examples to describe you how it is work
Check this tutorial too ..
http://plnkr.co/edit/FgBcahr6WKAI2oEgg4cO?p=preview
angular.module('todoApp', []).controller('TestController', function($scope, $http) {
var thisApp = this;
$scope.readedTodo = {};
this.noteupd = {};
thisApp.showUpd = function(noteID) {
// changed your url as defat json data
$http({
method: 'GET',
url: 'data.json'
})
.then(function(response) {
console.log(response.data);
console.log(response.data.content);
console.log(response.data.deadline);
console.log(response.data.id);
console.log(response.data.completed);
thisApp.noteupd = response.data;
$scope.readedTodo = response.data;
}, function() {
alert("Error getting todo note");
});
}
thisApp.updTodo = function(noteupd) {
console.log("TEST");
console.log(thisApp.noteupd);
}
});
<!doctype html>
<html ng-app="todoApp">
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div id="overlaybox" ng-controller="TestController as myControl">
<button ng-click="myControl.showUpd(4)">Test</button>
<br/>
<br/>
<br/>
<form ng-submit="myControl.updTodo()">
<h3>if you use binding h this against $scope</h3> Note:
<br/>
<textarea rows="5" cols="30" id="updContent" ng-model="myController.noteupd.content"></textarea>
<br/> Deadline (format YYYY-MM-DD HH:MM):
<br/>
<input type="text" id="updDeadline" ng-model="myController.noteupd.deadline" />
<br/> Completed:
<input type="checkbox" id="updCompleted" ng-model="myController.noteupd.completed" />
<br/>
<h3>if you use binding with $scope</h3> Note:
<br/>
<textarea rows="5" cols="30" id="updContent2" ng-model="readedTodo.content"></textarea>
<br/> Deadline (format YYYY-MM-DD HH:MM):
<br/>
<input type="text" id="updDeadline222" ng-model="readedTodo.deadline" />
<br/> Completed:
<input type="checkbox" id="updCompleted" ng-model="readedTodo.completed" />
<br/>
<input type="hidden" id="updID" ng-model="readedTodo.id" />
<br/>
<input type="submit" value="Update" />
</form>
</div>
<h3>SEction 2 </h3>
<div id="overlaybox2" ng-controller="TestController ">
<button ng-click="showUpd(4)">Test</button>
<button ng-click="showUpdate(4)">Test</button>
<br/>
<br/>
<br/>
<form ng-submit="updTodo()">
<h3>if you use binding h this against $scope</h3> Note:
<br/>
<textarea rows="5" cols="30" id="updContent" ng-model="readedTodo.content"></textarea>
<br/> Deadline (format YYYY-MM-DD HH:MM):
<br/>
<input type="text" id="updDeadline" ng-model="readedTodo.deadline" />
<br/> Completed:
<input type="checkbox" id="updCompleted" ng-model="readedTodo.completed" />
<br/>
<h3>if you use binding with $scope</h3> Note:
<br/>
<textarea rows="5" cols="30" id="updContent2" ng-model="readedTodo.content"></textarea>
<br/> Deadline (format YYYY-MM-DD HH:MM):
<br/>
<input type="text" id="updDeadline222" ng-model="readedTodo.deadline" />
<br/> Completed:
<input type="checkbox" id="updCompleted" ng-model="readedTodo.completed" />
<br/>
<input type="hidden" id="updID" ng-model="readedTodo.id" />
<br/>
<input type="submit" value="Update" />
</form>
</div>
</body>
</html>

Categories

Resources