angularjs: how to link to service.js file in template file - angularjs

I have currently included all service files and controller files in index.html in my angularJS application and it is working fine.
But I want to include the respective service file and controller file in the template file, so that unwanted files for the home page of my application will not be loaded in the initial load: thus decreasing the time to load the home page.
I have tried to do this, but the I could not get the json data from the service.
Here is what I have done so far
app.js
var app = angular.module('app', ['ngRoute'])
.config(function ($routeProvider, $locationProvider) {
$routeProvider.when('/books',
{
templateUrl:'app/templates/books.html',
controller:'booksController'
}).when('/games',
{
templateUrl: 'app/templates/games.html',
controller: 'gamesController'
});
$locationProvider.html5Mode(true);
});
eventData.js service file
app.factory('eventData', function ($http, $log, $q) {
return {
getEvent: function () {
var deferred = $q.defer();
$http({
method: 'GET', url: 'https://www.googleapis.com/books/v1/volumes?q=harry%20potter'
}).success(function (data, status, headers, config) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
},
getGames: function () {
var deferred = $q.defer();
$http({
method: 'GET', url: 'https://www.googleapis.com/books/v1/volumes?q=hunger%20games'
}).success(function (data, status, headers, config) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
}
};
});
eventController.js
'use strict';
app.controller("EventController", function EventController($scope,eventData) {
$scope.event = eventData.getEvent();
$scope.event.then(function(event) {
console.log(event);
$scope.items = event.items;
console.log($scope.items);
},function(status) {
console.log(status);
});
});
BooksController.js
'use strict';
app.controller("booksController", function booksController($scope, eventData) {
$scope.event = eventData.getEvent();
$scope.event.then(function (event) {
console.log(event);
$scope.items = event.items;
console.log($scope.items);
}, function (status) {
console.log(status);
});
});
books.html
<script src="app/controllers/eventController.js"></script>
<script src="app/controllers/booksController.js"></script>
<script src="app/services/eventData.js"></script>
<div style="padding-left: 20px;padding-right: 20px">
<div class="row">
<h3>Sessions</h3>
<ul style="list-style-type: none;">
<li ng-repeat="session in items">
<div class="row session">
<div class="well col-md-12">
<h4 class="well">{{session.volumeInfo.title}}</h4>
<h6 style="margin-top: -10px">{{session.volumeInfo.publishedDate}}</h6>
<span>Page Count: {{session.volumeInfo.pageCount}}</span><br />
<span>Authors: {{session.volumeInfo.authors}}</span>
<p>{{session.searchInfo.textSnippet}}</p>
</div>
</div>
</li>
</ul>
</div>
</div>
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<title>Airlines!</title>
<link href="Content/bootstrap.css" rel="stylesheet" />
<meta charset="utf-8">
<base href="/airlines/">
</head>
<body>
<div class="container">
<div class="navbar">
<div class="navbar-inner">
<ul class="nav">
<li>Harry Potter</li>
<li>Hunger Games</li>
</ul>
</div>
</div>
<ng-view></ng-view>
</div>
<link href="Content/bootstrap.min.css" rel="stylesheet" />
<script src="Scripts/angular.js"></script>
<script src="Scripts/angular-route.js"></script>
<script src="app/app.js"></script>
</body>
</html>
Can you identify what I am doing wrong?

Related

Not able to inject resolved object from ui-route change into the controller

I am trying to access an http get response called during route change using ui route. The resolve itself happens but i am unable to access the response. I have tried some approaches in "listcontroller" which is shown. I am using a sample httpget url found in the internet for test. Angular version: v1.2.32. ui-route: 1.0.15.
script.js
var app = angular.module("Rasp", ["ui.router"])
.config(['$stateProvider', '$urlRouterProvider',function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/home");
$stateProvider
.state("ipList", {
url: "/ipList",
templateUrl: "templates/list.html",
controller: "listController",
resolve: {
SensorIP : function($http){
$http.get('https://httpbin.org/ip')
.then(function(response){
console.log('res');
console.log(response);
return response.data.origin;
});
}
}
})
.state("home", {
url: "/home",
templateUrl: "templates/home.html",
controller: "homeController"
});
}])
.controller("RaspController", ['$scope', '$http', function ($scope, $http) {
$scope.getDetails = function () {
// $http.get('https://httpbin.org/ip')
// .then(function (response) {
// console.log(response);
// $scope.response = response;
// },
// function (error) { console.log(error); }
// );
// };
}])
.controller("homeController", ['$scope', function ($scope) {
}])
.controller("listController", ['$scope','SensorIP',function ($scope,SensorIP) {
$scope.sensorList = SensorIP;
var vm = this;
this.list1 = SensorIP;
var logfunc = function() {console.log($scope.sensorlist)};
}])
list.html
<div>
{{list1}}
{{sensorlist}}
<button class="btn btn-danger navbar-btn" ng-click="logfunc()">click</button>
</div>
home.html
<h4>Click on "Get IP List" to get the list of IPs</h4>
<a ui-sref="ipList"><button id="button" >Get IP List</button></a>
index.html
<!DOCTYPE html>
<head>
<title>Title(To be changed)</title>
<!--JS-->
<script type="text/javascript" src="../node_modules/angular/angular.js"></script>
<script type="text/javascript" src="../node_modules/#uirouter/angularjs/release/angular-ui-router.js"></script>
<script type="text/javascript" src="script.js"></script>
<!-- -->
<!--CSS-->
<link rel="stylesheet" href="../css/style.css">
<!-- -->
</head>
<body>
<div ng-app="Rasp">
<div ng-controller="RaspController">
<div class="sidenav">
<!--
<a ui-sref="home" id="dot-button"><button class="btn btn-danger navbar-btn" >Home</button></a>
<a ui-sref="ipList" id="dot-button"><button class="btn btn-danger navbar-btn" >IP List</button></a>
-->
<a ui-sref="home">home</a>
<a ui-sref="ipList" >ipList</a>
</div>
<div>
<ui-view id="uiview"></ui-view>
</div>
</div>
</div>
</body>

module is not finding

I am getting Cannot find module with name myapp,
actually the module creation and mapping of module with script code is correct then why I am facing this issue.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>AJAX with Servlets using AngularJS</title>
<script type="text/javascript" src=js/angular.min.js></script>
<script>
angular.module("myapp", []).controller('mycontroller', function ($scope, $http){
$scope.getDataFrmServer()=function(){
$http({
method:'GET';
url:'NGServlet';
}).success( function(data, status, header, config){
$scope.person=data;
}).error(function(data, status, header, config){
});
};
});
</script>
</head>
<body>
<div data-ng-app="myapp">
<div data-ng-controller="mycontroller">
<button data-ng-click="getDataFrmServer()">Fetch Data From Server</button>
<p>First Name: {{person.firstName}}</p>
<p>Second Name:{{person.secondName}}</p>
</div>
</div>
</body>
</html>
This is the working version. don't use ; in the object for your http call. Also your function definition was wrong.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>AJAX with Servlets using AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script>
angular.module("myapp", []).controller('mycontroller', function ($scope, $http){
$scope.getDataFrmServer = function(){
$http({
method:'GET',
url:'NGServlet'
}).success( function(data, status, header, config){
$scope.person=data;
}).error(function(data, status, header, config){
});
};
});
</script>
</head>
<body>
<div data-ng-app="myapp">
<div data-ng-controller="mycontroller">
<button data-ng-click="getDataFrmServer()">Fetch Data From Server</button>
<p>First Name: {{person.firstName}}</p>
<p>Second Name:{{person.secondName}}</p>
</div>
</div>
</body>
</html>
Your code is having issues:
Instead of ' , ' you have used ' ; ' in $http method and url .
Please use the updated code. Please do correct the function definition also.
<script>
angular.module("myapp", []).controller('mycontroller', function ($scope, $http){
$scope.getDataFrmServer = function(){
$http({
method:'GET',
url:'NGServlet'
}).success( function(data, status, header, config){
$scope.person=data;
}).error(function(data, status, header, config){
});
}
});
</script>
<body>
<div ng-app="myapp">
<div data-ng-controller="mycontroller">
<button data-ng-click="getDataFrmServer()">Fetch Data From Server</button>
<p>First Name: {{person.firstName}}</p>
<p>Second Name:{{person.secondName}}</p>
</div>
</div>
</body>

AngularJs doesn't work if I give a value to ng-app and ng-controller

I hope you may help me.
I'm quite new with Angular so I'm maybe making some stupid error but, when a give a value to ng-app, it doesn't work AngularJs.
I make here an example:
This is my home.html that doesn't work (when I say "doesn't work" I mean that I see printed "{{name}}" instead of its value).
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
var req={
method: 'POST',
url: 'http://localhost:8080/ConnectionDb/WebAppDbServlet',
data: {"nome":$scope.name}
}
var app=angular.module('noteApp', [])
app.controller('noteCtrl', function ($scope, $http){
$scope.addNote = function () {
$http(req).success(function(data, status, headers, config) {
$scope.nome = data;
}).error(function(data, status, headers, config) {
});
}
})
</script>
</head>
<body ng-app="noteApp">
<div ng-controller="noteCtrl">
<form>
<div>
Insert your name: <input type="text" name="name" data-ng-model="name"><br>
</div>
</form>
<p>Hola {{name}}</p>
</div>
</body>
</html>
but if I change it like this
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
var req={
method: 'POST',
url: 'http://localhost:8080/ConnectionDb/WebAppDbServlet',
data: {"nome":$scope.name}
}
var app=angular.module('noteApp', [])
app.controller('noteCtrl', function ($scope, $http){
$scope.addNote = function () {
$http(req).success(function(data, status, headers, config) {
$scope.nome = data;
}).error(function(data, status, headers, config) {
});
}
})
</script>
</head>
<body ng-app>
<div>
<form>
<div>
Insert your name: <input type="text" name="name" data-ng-model="name"><br>
</div>
</form>
<p>Hola {{name}}</p>
</div>
</body>
</html>
it goes perfectly as it should.
Any suggestion?
In your view you are using {{ name }} but inside of your controller you are putting the data inside of $scope.nome.
Just change $scope.nome > $scope.name
You are setting the req variable using $scope.name but at that point scope is not defined. If you open the console you will see an error about. Try this:
http://plnkr.co/edit/LqZNX8BYnCnbUD29YRfi?p=preview
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
var req={
method: 'POST',
url: 'http://localhost:8080/ConnectionDb/WebAppDbServlet',
}
var app=angular.module('noteApp', [])
app.controller('noteCtrl', function ($scope, $http){
$scope.addNote = function () {
req.data={"nome":$scope.name};
$http(req).success(function(data, status, headers, config) {
$scope.name = data;
}).error(function(data, status, headers, config) {
});
}
})
</script>
</head>
<body ng-app="noteApp">
<div ng-controller="noteCtrl">
<form>
<div>
Insert your name: <input type="text" name="name" data-ng-model="name"><br>
</div>
</form>
<p>Hola {{name}}</p>
</div>
</body>
</html>
the wrong variable name ("nome" instead of "name") is unrelated to your issue but it still need to be corrected
You are missing a " ; " after "var app=angular.module('noteApp', [])" so noteApp is not getting initialized.

Reduce the code redundancy in angularjs function

I am a calling function two time (I think which is not necessary) so how I can reduce the code so that my application performance will improve.
This is my code:
<!DOCTYPE html>
<html lang="en" ng-app="demo">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<script src="jq.js"></script>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
<title>find freelancer..</title>
</head>
<body>
<div ng-controller="myCtrl">
Experence Level: <br>
Entry level:<input type="checkbox" ng-click="myClick()">
<div ng-repeat="data in people">
{{data.name}}
</div>
</div>
<div ng-controller="myCtrl1">
Intermediate level:<input type="checkbox" ng-click="myClick1()">
<div ng-repeat="data in people">
{{data.sname}}
</div>
</div>
<script>
var app=angular.module('demo',[]);
app.controller('myCtrl',function($scope,$http)
{
$scope.myClick=function(event) {
$http.get("image.json")
.success(function(response){
$scope.people=response.jsonrecords;
});
}
});
app.controller('myCtrl1',function($scope,$http)
{
$scope.myClick1=function(event) {
$http.get("image.json")
.success(function(response){
$scope.people=response.jsonrecords;
});
}
});
</script>
</body>
</html>
As you are using same ajax request then it can be a proper candidate for making it a service/factory:
app.factory ('imgdata', ['$http', function(){
var result = $http.get('urlhere');
return result; // <--return it here.
});
Now imgdata can be injected:
app.controller('myCtrl',['$scope', 'imgdata', function($scope, imgdata){
$scope.myClick=function(event) {
imgdata.then(function (resp){
$scope.people = resp.data;
});
};
});
Same goes for other controller.
I think this is your target.. i hope helps you
var app = angular.module('demo', []);
app.controller('myCtrl', function($scope, appService) {
$scope.myClick = function(event) {
if ($scope.checkbox1) {
appService.get().success(function(response) {
//$scope.people = response;
});
} else {
$scope.people = [];
}
}
});
app.controller('myCtrl1', function($scope, appService) {
$scope.myClick1 = function(event) {
if ($scope.checkbox2) {
appService.get().success(function(response) {
//$scope.people = response;
});
} else {
$scope.people = [];
}
}
});
app.service("appService", function($http) {
this.get = function() {
return http({
url: "image.json",
method: "GET",
headers: {
'Content-Type': "application/json"
},
async: true
});
}
this.post = function() {
return http({
data: "////",
url: "url",
method: "POST",
headers: {
'Content-Type': "application/json"
},
async: true
});
}
//and .... edit .. delete
});
<!doctype html>
<html ng-app="demo">
<head>
</head>
<body>
<div ng-controller="myCtrl">
Entry level:
<input type="checkbox" ng-model="checkbox1" ng-change="myClick()">
<div ng-repeat="data in people">
{{data.name}}
</div>
</div>
<div ng-controller="myCtrl1">
Intermediate level:
<input type="checkbox" ng-model="checkbox2" ng-change="myClick1()">
<div ng-repeat="data in people">
{{data.name}}
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-rc.0/angular.js"></script>
</body>
</html>
Depending on how you might use it later, but for the moment I would create a service looking a bit like this
app.factory('getPeople', function($http) {
return function($scope) {
return function(event) {
$http.get('image.json').success(function(response) {
$scope.people = response.jsonrecords;
});
};
};
});
Then your controller is dead simple
app.controller('myCtrl',function($scope, getPeople) {
$scope.myClick = getPeople($scope);
});

angular js not waiting for rest response

I am new to angular js. I have to work with the rest calls in java. I have taken an example related to angularjs, java rest.
see app.js
angular.module('ngdemo', ['ngRoute','ngdemo.filters', 'ngdemo.services', 'ngdemo.directives', 'ngdemo.controllers']).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/user-list', {templateUrl: 'partials/user-list.html', controller: 'UserListCtrl'});
$routeProvider.when('/user-detail/:id', {templateUrl: 'partials/user-detail.html', controller: 'UserDetailCtrl'});
$routeProvider.when('/user-creation', {templateUrl: 'partials/user-creation.html', controller: 'UserCreationCtrl'});
}]);
controllers.js
'use strict';
/* Controllers */
var app = angular.module('ngdemo.controllers', []);
app.run(function ($rootScope, $templateCache) {
$rootScope.$on('$viewContentLoaded', function () {
$templateCache.removeAll();
});
});
app.controller('UserListCtrl', ['$scope', 'UsersFactory', 'UserFactory', 'DeleteUserFactory', 'UsersSearchFactory', '$location',
function ($scope, UsersFactory, UserFactory, DeleteUserFactory, UsersSearchFactory, $location) {
// callback for ng-click 'editUser':
$scope.editUser = function (userId) {
$location.path('/user-detail/' + userId);
};
$scope.searchUser = function () {
$scope.users = UsersSearchFactory.search($scope.user);
};
// callback for ng-click 'deleteUser':
$scope.deleteUser = function (user) {
DeleteUserFactory.delete(user);
$scope.users = UsersFactory.query({startRow: 0}, {endRow: 75});
};
// callback for ng-click 'createUser':
$scope.createNewUser = function () {
$location.path('/user-creation');
};
$scope.users = UsersFactory.query({startRow: 0}, {endRow: 75});
}]);
app.controller('UserDetailCtrl', ['$scope', '$routeParams', 'UserFactory', 'UpdateUserFactory', '$location',
function ($scope, $routeParams, UserFactory, UpdateUserFactory, $location) {
// callback for ng-click 'updateUser':
$scope.updateUser = function () {
UpdateUserFactory.update($scope.user);
$location.path('/user-list');
};
// callback for ng-click 'cancel':
$scope.cancel = function () {
$location.path('/user-list');
};
$scope.user = UserFactory.show({id: $routeParams.id});
}]);
app.controller('UserCreationCtrl', ['$scope', 'CreateUserFactory', '$location',
function ($scope, CreateUserFactory, $location) {
// callback for ng-click 'createNewUser':
$scope.createNewUser = function () {
CreateUserFactory.create($scope.user);
$location.path('/user-list');
}
}]);
services.js
'use strict';
/* Services */
var services = angular.module('ngdemo.services', ['ngResource']);
services.factory('UsersFactory', function ($resource) {
return $resource('/ngdemo/rest/getUsers/:startRow/:endRow', {}, {
query: { method: 'GET', isArray: true, params: {startRow: '#startRow', endRow: '#endRow'} },
create: { method: 'POST' }
})
});
services.factory('UsersCountFactory', function ($resource) {
return $resource('/ngdemo/rest/getUsersCount', {}, {
count: { method: 'GET'}
})
});
services.factory('UsersSearchFactory', function ($resource) {
return $resource('/ngdemo/rest/searchUser', {}, {
search: { method: 'POST', isArray: true, }
})
});
services.factory('CreateUserFactory', function ($resource) {
return $resource('/ngdemo/rest/registerUser', {}, {
create: { method: 'POST' }
})
});
services.factory('UpdateUserFactory', function ($resource) {
return $resource('/ngdemo/rest/updateUser', {}, {
update: { method: 'POST' }
})
});
services.factory('DeleteUserFactory', function ($resource) {
return $resource('/ngdemo/rest/deleteUser', {}, {
delete: { method: 'POST' }
})
});
services.factory('UserFactory', function ($resource) {
return $resource('/ngdemo/rest/findUserById/:id', {}, {
show: { method: 'GET' }
})
});
user-list.html
<div class="container">
<form novalidate="novalidate" class="form-horizontal">
<div class="control-group">
<label class="control-label" for="inputFirstName">First name:</label>
<div class="controls">
<input type="text" id="inputFirstName" ng-model="user.firstName" placeholder="First name"/>
</div>
</div>
<div class="form-group">
<div class="controls">
<a ng-click="searchUser()" class="btn btn-primary btn-xs">Search</a>
</div>
</div>
</form>
</div>
<div class="span6">
<table class="table table-striped table-condensed" >
<thead>
<tr>
<th style="min-width: 80px;"> First Name</th>
<th style="min-width: 80px;"> Last Name</th>
<th style="width:20px;"> </th>
<th style="width:20px;"> </th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users" > <!-- | orderBy:sort.sortingOrder:sort.reverse" > -->
<td>{{ user.firstName }}</td>
<td>{{ user.lastName }}</td>
<td><a ng-click="editUser(user.userId)" class="btn btn-small btn-primary">edit</a></td>
<td><a ng-click="deleteUser(user)" class="btn btn-small btn-danger">delete</a></td>
</tr>
</tbody>
</table>
<a ng-click="createNewUser()" class="btn btn-small">create new user</a>
</div>
index.html
<!doctype html>
<html lang="en" ng-app="ngdemo">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ngdemo app</title>
<link rel="stylesheet" href="css/app.css"/>
<link rel="stylesheet" href="css/bootstrap/bootstrap-responsive.min.css"/>
<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css"/>
</head>
<body>
<ul class="menu">
<li>user-list</li>
</ul>
<div ng-view></div>
<!-- JQuery ================================================================ -->
<script src="js/jquery/jquery-2.0.3.js"></script>
<!-- Bootstrap ============================================================= -->
<script src="js/bootstrap/bootstrap.js"></script>
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-resource.js"></script>
<script src="lib/angular/angular-route.js"></script>
<!-- AngularJS App Code ==================================================== -->
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>
<script src="js/directives.js"></script>
</body>
</html>
Question:
I am getting the rest call to server and it is sending the response.
When i open index.html it is displaying the out put on the page. When i click on edit(update) or delete buttons or create new user button, the user details are saved in the database but the changed data is not displayed on the table.
This is happened because after editing(updating) , deleting and creating new user the angular code is not waiting for the response from REST call. It immediately calls the $location.path('/user-list'); So old data is displayed in the table.
Please help me.
I have added the success call backs for all the methods update, create, delete as
$scope.createNewUser = function () {
CreateUserFactory.create($scope.user, function(response) {
$location.path('/user-list');
});
}

Resources