How to share data between controllers in AngularJS? [duplicate] - javascript

This question already has answers here:
Share data between AngularJS controllers
(11 answers)
Closed 6 years ago.
I have a team_list page and a team page. A user will have a list of teams they are in in the team_list page and then click on one of the teams to go to its team page. I am not sure how to send the data that the team page that the user is going to is Team A's teampage or Team B's team page. So how do I share data between controllers?
I know I should be using services but I'm not sure how to use them in this context..I've tried some methods and commented out some but I'm still not sure how to go about this.
Using node.js and express framework for backend
team_list.html:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<head>
<title>Team List</title>
</head>
<body>
<h1>
Welcome to Your Team List Page!
</h1>
<!--<div ng-app="teamListPage" ng-controller="listController">
<fieldset>
<legend>Your Teams</legend>
<ul>
<li ng-repeat="x in [dave, david, darrell]">{{x}}</li>
<input type="button" id="enter" name="enter" value="Enter Home Page" ng-click="enterTeamPage()"/>
</ul>
</fieldset>
</div>-->
<div ng-app="teamListPage" ng-controller="listController">
<li ng-repeat="x in records">
{{x.team_name}}<br/>
<input type="button" id="enter" name="enter" value="Enter Home Page" ng-click="enterTeamPage()"/>
</li>
<input type="button" id="Create" name="Create" value="Create New Team" ng-click="enterCreateTeamPage()" />
</div>
<script>
var page = angular.module('teamListPage', []);
/*page.factory('myService', function() {
var user_id = [];
var setUserID = function(newObj) {
user_id.push(newObj);
};
var getUserID = function(){
return user_id;
};
return {
setUserID: setUserID,
getUserID: getUserID
};
});*/
page.factory('myService', function(){
return {
data: {
user_ID: ''
},
update: function(userID) {
// Improve this method as needed
this.data.user_ID = userID;
}
};
});
page.controller('listController', function($scope, $http, $window, myService) {
console.log(myService.data);
var login_http = $http({
method: 'GET',
url: '/team_req',
params: { user_id: 1 }
}).then(
function (response) {
//$window.alert(response.data[0].team_name);
$scope.records = response.data;
//console.log($scope.records[1]);
//alert('successfull ...');
}, function (response) {
$window.alert('wrong username/password');
}
)
$scope.enterTeamPage = function() {
$window.location.href = '/teamPage';
};
$scope.enterCreateTeamPage = function() {
$window.location.href = '/createTeamPage';
};
})
</script>
</body>
</html>
team_page.html:
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<head>
<meta charset="UTF-8">
<title>Team Page</title>
</head>
<body>
<h1>
Team Page
</h1>
<div ng-app="teamPage" ng-controller="teamController">
<form id="Communication Board">
<fieldset>
<legend>COMMUNICATION BOARD</legend>
<h3>
chat feature coming up!
</h3>
<legend>videocall</legend>
<h4>
video call feature coming up!
</h4>
<legend>screenshare</legend>
<h5>
screenshare feature coming up!
</h5>
</fieldset>
</form>
<form id="Data Board" action="">
<fieldset>
<legend>DATA BOARD</legend>
<h6>
calendar feature coming up!
</h6>
<legend>announcements</legend>
<h7>
All features are coming up very soon!
</h7>
</fieldset>
</form>
<p>
<input type="button" id="CodingZone" name="CodingZone" value="Go to Coding Zone" ng-click="enterCodingPage()" />
</p>
</div>
<script>
var page = angular.module('teamPage', []);
page.controller('teamController', function($scope, $http, $window) {
//get the history of the chat board
$scope.getChatHistory = function() {
var create = $http({
method: 'Get',
url: '/chatHistory'
}).then(
function successful(response) {
$scope.theResponse = response.data;
}, function unsuccessful(response) {
alert('got an error back from server');
$scope.theResponse = response;
});
}
$scope.enterCodingPage = function() {
$window.location.href = '/codingPage';
};
})
</script>
</body>
</html>
Also should I put my service in app.js or index.js?

The best way to share data between controllers or components (wrappers for directives) is to use angular services and inject them into controllers. Cuz services are singletons so each of them presents single state for all components where it will be injected.

Related

update the data dynamically in AngularJS

I have two end points
http://localhost:3000/entry (POST)
Keys are :- fname, lname and age . We can submit a form by sending a POST request to this URL.
http://localhost:3000/entries (GET)
It will return the existing data from the database in a JSON.
[
{
"_id": "5b48a137c3b2a3454b853a3c",
"fname": "John",
"lname": "Jose",
"age": "28",
"__v": 0
},
{
"_id": "5b506cc7d9105012f59c87e6",
"fname": "Alex",
"lname": "Cruz",
"age": "27",
"__v": 0
}
]
I can successfully submit a form. In my HTML, I also have a table. I want to update the data in the table whenever I submit an entry without reloading the whole page.
Actually, data in this API http://localhost:3000/entries is dynamic, sometimes, I insert into database directly. So, whenever there is a change, it should reflect in the table without reloading the whole page.
I am using AngularJS 1.
index.html :-
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="script.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="style.css">
<div ng-app="myApp">
<div class="container">
<div class="row">
<div class="col-sm-12">
<h3>
Dashboard
</h3>
</div>
</div>
<form name="saveTemplateData" action="#" ng-controller="FormCtrl" ng-submit="submitForm()" >
<div class="col-sm-12">
<div class="form-group">
<label>FirstName</label>
<input type="text" class="form-control" value="" ng-model="form.fname" />
</div>
<div class="form-group">
<label>LastName</label>
<input type="text" class="form-control" value="" ng-model="form.lname" />
</div>
<div class="form-group">
<label>Age</label>
<input type="text" class="form-control" value="" ng-model="form.age" />
</div>
</div>
<div class="col-sm-12">
<input type="submit" class="btn btn-success" ngClick="Submit">
</div>
</form>
<!-- Table Start -->
<div class="row">
<table style="width:100%">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<tr>
<!-- item.fname -->
<td>{{item.fname}}</td>
<!-- item.lname -->
<td>{{item.lname}}</td>
<!-- item.age -->
<td>{{item.age}}</td>
</tr>
</table>
</div>
<!-- Table END -->
</div>
</div>
script.js :-
var app = angular.module('myApp', []);
app.controller('FormCtrl', function ($scope, $http) {
$scope.submitForm = function()
{
$http({
url: "http://localhost:3000/entry",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param($scope.form)
}).then(function (response) {
$scope.status = status;
}), function (error) {
$scope.status = status;
};
}
});
If I understand your question and problem(s), you'll need to do a number of things to resolve your issues.
Firstly, you'll want to make some extensions to your controller. The main one being to fetch the data from your API:
app.controller('FormCtrl', function ($scope, $http, $interval) {
/*
Add this method to get data from server
*/
$scope.fetchData = function() {
// It is best practice to handle error responses as well (not
// shown here)
$http.get('http://localhost:3000/entries').then(function(response) {
// Set the data items in your scope. Doing this should now
// cause them to be listed in your view
$scope.items = response.data;
});
}
$scope.submitForm = function($event) {
// Adding this prevents the browser from reloading on form submit
$event.preventDefault()
$http({
url: "http://localhost:3000/entry",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param($scope.form)
}).then(function (response) {
$scope.status = status;
}), function (error) {
$scope.status = status;
});
}
// Fetch data once controller is set up, on a regular 2 second
// interval
$interval(function() {
$scope.fetchData()
}, 2000)
});
You'll also need to update your HTML/view:
<!-- Add $event as an argument to you ng-submit callback -->
ng-submit="submitForm($event)"
And:
<!-- Doing this causes the data in the items array to be iterated
and displayed in a list-wise fashion in the table -->
<tr ng-repeat="item in items">
<!-- item.fname -->
<td>{{item.fname}}</td>
<!-- item.lname -->
<td>{{item.lname}}</td>
<!-- item.age -->
<td>{{item.age}}
</td>
</tr>
Finally, the most important thing is to wrap the table and form with your FormCtrl controller. You can do this by moving ng-controller="FormCtrl" from your <form> element, to your <div class="container"> element in your view.

Sending form with optional parameters POST-method + angularJS

I'm trying to make a form that sends an url of the type /:id/:option where I know the id before entering the form but the option-attribute is the one that the user selects from the radio-buttons. After submitting the form I should move to the page /:id/:option. I'm also using angulasJS with my application.
So how can I send the url with the POST-method?
html
<form method="POST">
<div class="voteOptions" ng-repeat="item in id.data.options">
<label class="radioButtons">{{item.title}} votes:{{item.votes}}
<input type="radio" name="option" value={{item.option}}>
<span class="radioSelector"></span>
</label>
</div>
<input type="submit" id="voteSubmit" value="Vote!">
</form>
.post-call
app.post('/:id/:option', (req, res) => {
var poll = polls[req.params.id-1];
poll.options[req.params.option-1].votes++;
res.json(poll);
});
Create Controller and make Http call from there.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<form method="POST" ng-submit="submit()">
<div class="voteOptions" ng-repeat="item in options">
<label class="radioButtons">{{item.title}} votes:{{item.votes}}
<input type="radio" name="option" value={{item.option}} ng-model="option.val">
<span class="radioSelector"></span>
</label>
</div>
<input type="submit" id="voteSubmit" value="Vote!">
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$http) {
var id = 12345;
$scope.option = {val:0};
$scope.options= [{
title : 'option-1',
votes : 5,
option : 1
},{
title : 'option-2',
votes : 5,
option : 2
}];
$scope.submit = function(){
console.log('Url', `<domain>/${id}/${$scope.option.val}`);
// Generate url and call http post
// $http.post(url, body, config)
// .success(function (data, status, headers, config) {
// })
// .error(function (data, status, header, config) {
// });
}
});
</script>
</body>
</html>

angularjs 1 manual bootstrap doesnot work

I am new to angularjs.
I tried to create 2 different modules in an single js file and them manually bootstrap one of them to a element. This was suggested in one of the stackoverflow questions. But this doesnot seem to work.
Both of the modules work fine independently.
I am not sure what is going wrong here.
Here's my code :-
myApp.js
var app = angular.module("myApp", []);
var myController = app.controller("ctrl1", function($scope){
"use strict";
$scope.fname = "Bill";
$scope.lname = "Goldberg";
$scope.updatevalue = function () {
$scope.fullname = $scope.fname + $scope.lname;
//$scope.fname = "newName"
};
});
app.directive("w3TestDirective", function() {
"use strict";
return {
template : "<h1>This is my life!</h1>"
};
});
var loginController = angular.module('loginController', []);
loginController.controller('loginCntrl', function ($scope) {
"use strict";
$scope.username="email";
$scope.password="password";
$scope.present = false;
$scope.login = function () {
"use strict";
if ($scope.username == "Amar" & $scope.password == "Amar") {
$scope.present=true;
$scope.loginMessage = "logged in successfully";
} else {
$scope.present=true;
$scope.loginMessage = "Invalid username or password";
}
}
});
angular.bootstrap(document.getElementById("loginDiv"),['loginController']);
Index.html
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<!--script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-route.js"></script-->
<script src="scripts/services/myApp.js"></script>
<!--script src="scripts/services/login.js"></script-->
<body>
<div id="demoDiv" ng-app="myApp" ng-controller="ctrl1">
<span>Values:</span>
<input type="text" ng-model="fname"/>
<input type="text" ng-model="lname"/>
<button ng-click="updatevalue()">fullname</button>
<br></br>
{{ fullname }}
<br></br>
<w3-test-directive></w3-test-directive>
</div>
<br></br>
<div id="loginDiv" ng-app="loginController" ng-controller="loginCntrl">
<input type="text" ng-model="username"/>
<input type="text" ng-model="password"/>
<button ng-click="login()">submit</button>
<br></br>
<div ng-if="present"> {{ loginMessage }} </div>
</div>
</body>
</html>
This is the completely wrong approach. You CAN have your controllers in more than one module, but you should always have a single module which is the main parent for the app.
Let's Assume myApp is your parent module, and make some changes:
First, move the ng-app to the body element:
<body ng-app="myApp">
<div id="demoDiv" ng-controller="ctrl1">
...
Next, remove ng-app from the loginDiv:
<div id="loginDiv" ng-controller="loginCntrl">
Finally, inject the loginController module into the myApp module:
var app = angular.module("myApp", ['loginController']);
Now, the app will be able to attach both controllers without issue.
http://plnkr.co/edit/rkFY0ASCHaQUTByaHJg3?p=preview
I fixed my issue with the following code :-
var app = angular.module("myApp", ['utilModule','loginModule']);
var myController = app.controller("ctrl1", function($scope){
"use strict";
$scope.fname = "Bill";
$scope.lname = "Goldberg";
$scope.updatevalue = function () {
$scope.fullname = $scope.fname + $scope.lname;
//$scope.fname = "newName"
};
});
app.directive("w3TestDirective", function() {
"use strict";
return {
template : "<h1>This is my life!</h1>"
};
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<!--script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-route.js"></script-->
<script src="scripts/services/myApp.js"></script>
<script src="scripts/services/util.js"></script>
<script src="scripts/services/login.js"></script>
<body ng-app="myApp">
<div id="demoDiv" ng-controller="ctrl1">
<span>Values:</span>
<input type="text" ng-model="fname"/>
<input type="text" ng-model="lname"/>
<button ng-click="updatevalue()">fullname</button>
<br></br>
{{ fullname }}
<br></br>
<div ng-controller="utilCntrl">
{{ test }}
<testDirective></testDirective>
</div>
<w3-test-directive></w3-test-directive>
</div>
<br></br>
<div id="loginDiv" ng-controller="loginCntrl">
<input type="text" ng-model="username"/>
<input type="text" ng-model="password"/>
<button ng-click="login()">submit</button>
<br></br>
<div ng-if="present"> {{ loginMessage }} </div>
</div>
</body>
</html>
There is only 1 issue, the testDirective tag doesnot print anything on the browser. but that is not a requirement, so I will just ignore this for the time being.
I realize that this is what #Claies has posted. Claies, Thank you very much for your time and effort.
You can't use the ng-app directive and angular.bootstrap function to bootstrap you angular application. You either use ng-app or angular.bootstrap.
If you have two modules "myApp" and "loginController" like you do in your app, you must make "loginController" a dependency of "myApp". "myApp" will be your angular application module that you can add more dependencies, external or custom.
angular.module('myApp', ['loginController', 'ui-router', 'etc'...])

Angularjs - Displaying data using $http get from remote server

i want to send a http get request which is not a problem.
But the problem is i want to disply the data from the server page. Does it has to be a JSON page to display the data from remote server ? or any sort of data can be displayed ? if yes , then how
Thank you
<div class="form" ng-app="myApp" ng-controller="myCtrl">
<p>Enter URL : <input type="text" ng-model="url" /></p>
<p><input type="submit" value="CHECK" ng-click="callAPI()" /> </p> <!-- 1 -->
<p>
<ul ng-repeat="post in posts">
<li>{{post}}</li>
</ul>
</p>
<div ng-bind="result"></div> <!-- 5 -->
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.callAPI = function() { // 2
//console.log($scope.url); //3
$http.get($scope.url)
.success(function(response) {
$scope.posts = response.data; //4
});
};
});
</script>
</body>
</html>
another version of code
<div class="form" ng-app="myApp" ng-controller="myCtrl">
<p>Enter URL : <input type="text" ng-model="url" /></p>
<p><input type="submit" value="CHECK" ng-click="callAPI()" /> </p>
<div ng-bind="result"></div> <!-- 5 -->
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.$watch('url', function() {
fetch();
});
function fetch() {
console.log($scope.url);
$http.get($scope.url)
.success(function(response) {
$scope.result = response.data;
});
}
$scope.callAPI= function() {
this.setSelectionRange(0, this.value.length);
}
});
</script>
</body>
</html>
Like the comments says, I believe that angular look at the content Type of the response to parse the data. Have you try added the accept header type?
What is the content type of the response?
var req = {
method: 'GET',
url: 'http://example.com',
headers: {
'Accept': change this to whatever content you want to accept
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
hey i have found my answer of my question ...
there was a mistake in the source code
here is the right one
<div class="form" ng-app="myApp" ng-controller="myCtrl as controller">
<p>Enter URL : <input type="text" ng-model="url" /></p>
<p><input type="submit" value="CHECK" ng-click="clickButton()" /> </p>
<p>
<ul>
<li ng-repeat="data in result">
{{data}}
</li>
</ul>
</p>
</div>
and
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.clickButton = function() {
console.log($scope.url);
$http.get($scope.url)
.then(function(response) {
$scope.result = response.data;
});
};
});
</script>
:)
if anyone has a similer problem , i hope this answer will help ..
cheers
function functionName(){
$http.get(URL).success(function(response){
$scope.variable = response;
})
}
inside get() put your url, if your url returning any data then it will go to success() function.

AngularJS move part of Controller to Service

Consider the following code.
HTML:
<!doctype html>
<html ng-app="todoApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="/css/bootstrap.min.css" rel="stylesheet">
<link href="/css/overlay-control.css" rel="stylesheet">
<link href="/css/list-control.css" rel="stylesheet">
<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="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!--<script src="/js/Services/UserService.js"></script>-->
<script src="/js/Controllers/MainController.js"></script>
<!--<script src="/js/Controllers/UserController.js"></script>-->
<script src="/js/bootstrap.min.js"></script>
</head>
<body ng-controller="MainController as myControl">
<div id="overlaycover" ng-click="myControl.showUpd(0)"></div>
<div id="overlaybox">
<div class="col-md-12">
<h4>Update:</h4>
<form ng-submit="myControl.updTodo()">
<div class="form-group">
<label for="updContent">Note:</label>
<textarea rows="5" cols="30" class="form-control" id="updContent" name="updContent" ng-model="noteupd.content"></textarea>
</div>
<div class="form-group">
<label for="updDeadline">Deadline (format YYYY-MM-DD HH:MM:SS):</label>
<input type="text" class="form-control" id="updDeadline" name="updDeadline" ng-model="noteupd.deadline" />
</div>
<div class="checkbox">
<label>
<input type="checkbox" id="updCompleted" name="updCompleted" ng-model="noteupd.completed" /> - Completed
</label>
</div>
<div class="form-group">
<input type="hidden" id="updID" ng-model="noteupd.id" /><br/>
<button type="submit" class="btn btn-info">Update</button>
</div>
</form>
Click utside the square to close.
</div>
</div>
<div class="container">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12" id="listDiv">
<h1>Todo-list:</h1>
<p>
<img src="/images/legend-normal.png"> - Unfinished 
<img src="/images/legend-completed.png"> - Finished 
<img src="/images/legend-late.png"> - Late
</p>
<table class="table" id="list-table">
<tr>
<th>Note:</th>
<th>Author:</th>
<th>Project:</th>
<th>Created:</th>
<th>Deadline:</th>
<th colspan="2">Modify:</th>
</tr>
<tr ng-repeat="todo in myControl.todos" ng-class="rowClass(todo.completed, todo.deadline)">
<td> {{ todo.content }} </td>
<td> {{ todo.user }} </td>
<td> {{ todo.project }} </td>
<td> {{ todo.created }} </td>
<td> {{ todo.deadline }} </td>
<td><button type="button" class="btn btn-info" ng-click="myControl.showUpd(todo.id)">Update</button></td>
<td><button type="button" class="btn btn-danger" ng-click="myControl.delTodo(todo.id)">Delete</button></td>
</tr>
</table>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12" id="formDiv">
<h3>Add new note:</h3>
<form ng-submit="myControl.addTodo()">
<div class="form-group">
<label for="newUser">User:</label>
<select ng-model="noteadd.user" class="form-control" id="newUser" name="newUser">
<option ng-repeat="user in myControl.users" value="{{ user.id }}">{{ user.name }}</option>
</select><br/>
</div>
<div class="form-group">
<label for="newProject">Project:</label>
<select ng-model="noteadd.project" class="form-control" id="newProject" name="newProject">
<option ng-repeat="project in myControl.projects" value="{{ project.id }}">{{ project.name }}</option>
</select><br/>
</div>
<div class="form-group">
<label for="newContent">Note:</label>
<textarea rows="5" cols="30" ng-model="noteadd.content" class="form-control" id="newContent" name="newContent"></textarea><br/>
</div>
<div class="form-group">
<label for="newDeadline">Deadline (format YYYY-MM-DD HH:MM:SS):</label>
<input type="text" ng-model="noteadd.deadline" class="form-control" id="newDeadline" name="newDeadline" /><br/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-info">Add</button>
</div>
</form>
</div>
</div>
</body>
</html>
AngularJS Controller:
angular.module('todoApp', []).controller('MainController', function($scope, $http) {
var thisApp = this;
$scope.noteadd = {};
var noteadd = $scope.noteadd;
$scope.noteupd = {};
var noteupd = $scope.noteupd;
// Get all notes:
$http({method : 'GET', url : 'http://localhost:8000/notes'})
.then (function(response) {
thisApp.todos = response.data;
}, function() {
alert("Error getting todo notes");
});
// Get all users:
$http({method : 'GET',url : 'http://localhost:8000/users'})
.then(function(response) {
thisApp.users = response.data;
}, function() {
alert("Error getting users");
});
// Get all projects
$http({method : 'GET', url : 'http://localhost:8000/projects'})
.then(function(response) {
thisApp.projects = response.data;
}, function() {
alert("Error getting projects");
});
// Add note to database
thisApp.addTodo = function(noteadd)
{
$http({
method : 'PUT',
url : 'http://localhost:8000/notes',
data : $.param($scope.noteadd),
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function(response) {
location.reload();
}, function() {
alert("Couldn't add note. Please try again!");
});
};
// Hide note by setting removed to 1
thisApp.delTodo = function(noteID)
{
var r = confirm("Are you sure?");
if (r == true) {
var noteObj = JSON.parse('{"id":' + noteID + '}'); // JSON for req
$http({
method : 'DELETE',
url : 'http://localhost:8000/notes',
data : $.param(noteObj),
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function(response) {
location.reload();
}, function() {
alert("Couldn't delete note. Please try again!");
});
}
};
// Show overlay with form for updating a note
thisApp.showUpd = function(noteID)
{
var overlaycover = document.getElementById("overlaycover");
var overlaybox = document.getElementById("overlaybox");
overlaycover.style.opacity = .65;
if(overlaycover.style.display == "block" || noteID == 0){ // For toggling overlay
overlaycover.style.display = "none"; // Hide div overlaycover
overlaybox.style.display = "none"; // Hide div overlaybox
} else {
$http({method : 'GET', url : 'http://localhost:8000/notes/' + noteID})
.then (function(response) {
noteupd.content = response.data.content; // Update fields in form
noteupd.deadline = response.data.deadline;
noteupd.id = response.data.id;
if (response.data.completed == 1) {
noteupd.completed = true;
} else {
noteupd.completed = false;
}
overlaycover.style.display = "block"; // Show div overlaycover
overlaybox.style.display = "block"; // Show div overlaybox
}, function() {
alert("Error getting todo note");
});
}
}
// Update a note
thisApp.updTodo = function(noteupd)
{
$http({
method : 'POST',
url : 'http://localhost:8000/notes',
data : $.param($scope.noteupd),
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function(response) {
location.reload();
}, function() {
alert("Couldn't add note. Please try again!");
});
}
// Check if deadline passed for each note in list
$scope.rowClass = function(completed, deadline)
{
var nowTime = Math.floor(Date.now()/1000);
var deadTime = new Date(deadline);
var deadUTC = Math.floor(deadTime/1000);
if (completed == 1) {
return "success"; // Note is completed
} else if (deadUTC < nowTime) {
return "danger"; // Note is not completed, deadline passed
} else {
return "active"; // Note is not completed, still time left
}
}
});
What I would like to do is to move all $http-calls to a service instead of having them in the controller like I have it now. I have searched the internet but I don't really understand the solutions i've found there.
Second, in several functions, as you can see, I use location.reload();. I would like to use ng-bind instead, but as the sam, I don't understand how this works.
Can someone please explain how I should do these two things?
Ok , let's for example create a Users factory and put all Users api related stuff inside:
'use strict';
angular
.module('todoApp')
.factory('Users', factory);
function factory($http) {
var service = {
get: get,
//edit: edit ...
};
return service;
function get() {
return $http({method : 'GET',url : 'http://localhost:8000/users'})
.then(function(response) {
return response.data;
});
}
//function edit(user) {
// return $http({method : 'PUT...
//}
}
What you have to do next is inject that factory wherever you want to call it.
So in your controller you essentially have to do this:
angular.module('todoApp', [])
.controller('MainController', function($scope, Users) {
//.....
function getUsers() {
Users.get().then(function(data){
thisApp.users = response.data;
}, function() {
alert("Error getting users");
});
}
getUsers();
//...
Repeat the same by creating the appropriate services for notes and projects.
To not bloat the main app.js move this services to seperate files, users.service.js etc..
I would also advise you to move the controllers to seperate files too.
Just be careful:
this is a module creation
angular.module('todoApp', [])
You create a module once.
to attach a service/factory/controller/anything, when you are in that separate file, to that module you use this:
angular.module('todoApp').anything
Second, I assume you use location.reload to update the view with the new data.
Let's say you edit/delete a User. Instead of reloading the page, call getUsers() in the then() of put/delete/create User.
Hope it makes sense to you!
PS: This styleguide by John Papas have been very helpful to me, I suggest you give it a read !
I've already used service factory solution for such kind of problem.
angular.module('data-service').factory('dataService', ['$http',function ($http) {
var url = 'http://localhost:8000/';
return {
getData: function(type) {
return $http({method : 'GET', url : url + type});
},
allData: function() {
return $q.all({
notes: this.getData('notes'),
users: this.getData('users'),
projects: this.getData('projects')
});
}
}
}]);
usage:
dataService.getData('notes').then(function (data) { ... });
also you can use angular promise $q.
dataService.allData().then(function(data) { /* data.notes, data.users, data.projects */ }

Categories

Resources