angular controller by module blank page - javascript

hello i have a problem with angular im benninger to this framework but i have some knowledge about it . Yesterday i faced a problem when i wanted to change controller from a global function(in this case all is OK) to controller by module i recive blank page here is my code
angular.module('myApp', ['ngRoute', 'membersService']).config(
['$httpProvider', '$routeProvider', function ($httpProvider, $routeProvider) {
$routeProvider.when('/home', {
templateUrl: 'partials/home.html',
controller: MembersCtrl
}).otherwise({
redirectTo: '/home'
});
}]);
var myApp = angular.module('myApp');
myApp.controller('MembersCtrl',['$scope','$http', 'MembersSrv',function ($scope, $http, MembersSrv) {
$scope.refresh = function () {
return MembersSrv.getAllPersons().then(function (data) {
$scope.persons = data.data;
});
};
$scope.clearMessages = function () {
$scope.successMessages = '';
$scope.errorMessages = '';
$scope.errors = {};
};
$scope.reset = function () {
if ($scope.regForm) {
$scope.regForm.$setPristine();
}
$scope.newPerson = {name: "", lname: "", phoneNumber: ""};
$scope.clearMessages();
};
$scope.register = function () {
$scope.clearMessages();
MembersSrv.save($scope.newPerson, function (data) {
$scope.refresh();
$scope.reset();
$scope.successMessages = ['Member Registered'];
}, function (result) {
if ((result.status == 409) || (result.status == 400)) {
$scope.errors = result.data;
} else {
$scope.errorMessages = ['Unknown server error'];
}
});
};
$scope.refresh();
$scope.reset();
$scope.orderBy = 'name';
}]);
angular.module('membersService', []).service('MembersSrv', [
'$http', function ($http) {
this.getAllPersons = function () {
var url = "http://localhost:8080/gadziksy-web/rest/person";
var req = {
method: 'GET',
url: url,
};
return $http(req);
}
}]);
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<title>myApp</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<!-- Disable phone number detection on iOS. -->
<meta name="format-detection" content="telephone=no"/>
<link rel="stylesheet" href="css/screen.css" type="text/css"/>
<!-- Load angularjs -->
<script src="js/libs/angular.js"></script>
<!-- Load angularjs-route, which allows us to use multiple views displayed through application routes -->
<script src="js/libs/angular-route.js"></script>
<!-- Load angularjs-resource, which allows us to interact with REST resources as high level services -->
<script src="js/libs/angular-resource.js"></script>
<!-- Load the controllers for our app -->
<script src="js/controllers/MemberCtrl.js"></script>
<!-- Load the application wide JS, such as route definitions -->
<script src="js/app.js"></script>
<!-- Load the services we have defined for the application, particularly the REST services -->
<script src="js/services/MemberSrv.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<div ng-controller="MembersCtrl">
<h1 align="center">International Bank Application</h1>
<div>
<p>You have successfully connected to the Application.</p>
</div>
<form name="regForm" ng-submit="register()">
<h2>Member Registration</h2>
<fieldset>
<legend>Register a member:</legend>
<div>
<label for="name">Name:</label>
<input type="text" name="name" id="name" ng-model="newPerson.name" placeholder="Your Name" required
autofocus/>
</div>
<div>
<label for="lname">Lname:</label>
<input type="text" name="lname" id="lname" ng-model="newPerson.lname" placeholder="Your Lastname"
required/>
</div>
<div>
<label for="dob">Date</label>
<input type="date" name="dob" id="dob" ng-model="newPerson.dob" placeholder="Your Date" required/>
</div>
<ul ng-hide="!successMessages" class="success">
<li ng-repeat="message in successMessages">{{message}}</li>
</ul>
<ul ng-hide="!errorMessages" class="error">
<li ng-repeat="message in errorMessages">{{message}}</li>
</ul>
<div>
<input type="submit" ng-disabled="regForm.$invalid" id="register" value="Register"/>
<input type="button" ng-click="reset()" name="cancel"
id="cancel" value="Cancel"/>
</div>
</fieldset>
</form>
<h2>Persons</h2>
<em ng-show="persons.length == 0">No registered members.</em>
<table ng-hide="persons.length == 0" class="simpletablestyle">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Lname</th>
<th>Date</th>
<th>REST URL</th>
</tr>
</thead>
<tr ng-repeat="person in persons | orderBy:orderBy">
<td>{{person.id}}</td>
<td>{{person.name}}</td>
<td>{{person.lname}}</td>
<td>{{person.dob}}</td>
<td>details-{{person.id}}
</td>
</table>
<div>
REST URL for all members: /rest/members
</div>
<div>
<input type="button" ng-click="refresh()" name="refresh"
id="refresh" value="Refresh"/>
</div>
</div>

Change controller: MembersCtrl to controller: 'MembersCtrl' in $routeProvider config

Related

$injector:modulerr Failed to instantiate module bookApp due to: ReferenceError: 'when' is undefined at Anonymous function

I am building an angularjs app which starts from a login page but when I execute my login page,i get below error in console.
[$injector:modulerr] Failed to instantiate module bookApp due to:
ReferenceError: 'when' is undefined
at Anonymous function
PFB The relevant files.Any help is much appreciated.Thanks in advance.
P.S. Please let me know if any more information is required.
HTML :
<!doctype html>
<!--Mention the module name to <html> -->
<html ng-app="bookApp">
<head>
<title>Angular Assignment</title>
<style type="text/css">
#import "styles/style.css";
</style>
<script src="lib/Angular/angular.js"></script>
<script src="lib/Angular/angular-route.js"></script>
<script src="js/controllers.js"></script>
<script src="js/app.js"></script>
</head>
<body>
<center>
<!--include header.html -->
<div ng-include="'Header.html'"></div>
</center>
<!-- Add the required controller to this div.
Associate the models for username and password.-->
<div align="center" ng-controller="LoginCtrl">
<h2> Login </h2>
<div class="LoginFormDiv">
<table border="0">
<tr>
<td> Username </td>
<td>:
<input ng-model="username" class="input" placeholder="Enter Username"/>
</td>
</tr>
<tr>
<td> Password</td>
<td>:
<input ng-model="password" class="input" placeholder="Enter Password"/>
</td>
</tr>
<tr>
<td colspan="2">
<!-- On click of the button, call validate(user) method declared in controller-->
<input type="submit" class="button" value="Login" ng-click="validate()"/>
</td>
</tr>
</table>
</div>
</div>
<!-- include footer.html -->
<center>
<div ng-include="'Footer.html'"></div>
</center>
</body>
</html>
Controller.js
var Controllers = angular.module('Controllers', ['ngRoute']);
Controllers.controller('LoginCtrl', ['$scope', '$location', '$http', '$rootScope',
function($scope, $location, $http, $rootScope) {
alert("I am in LoginCtrl")
$scope.validate = function() {
alert("I am in validate function");
$http.get('data/roles.json').success(function(data) {
$scope.roles = data;
});
var count = 0;
angular.forEach($scope.roles, function(role) {
if ($scope.username == role.username && $scope.password == role.password) {
alert("login successful");
count = count + 1;
if ($scope.roles == "student") {
$location.path("/home/student");
} else {
$location.path("/home/librarian");
}
} else if (count != 1) {
alert("Please provide valid login credentials");
$location.path("/main")
}
});
}
}]);
app.js
var bookApp = angular.module('bookApp', ['Controllers', 'ngRoute']);
bookApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.when('/main', {
templateUrl : 'Login',
controller : 'LoginCtrl'
}).when('/home/student', {
templateUrl : 'ViewBooks_Student.html',
controller : 'BookListCtrl_Student'
});
when('/home/librarian', {
templateUrl : 'ViewBooks_Librarian.html',
controller : 'BookListCtrl_Librarian'
});
when('/issue/:bookId', {
templateUrl : 'IssueBook.html',
controller : 'IssueBookCtrl'
});
when('/return/:bookId', {
templateUrl : 'ReturnBook.html',
controller : 'ReturnBookCtrl'
});
otherwise({
redirectTo : '/main'
});
}]);
routeProvider.when().when().when() works.
routeProvider.when();when();when() doesn't. Semicolons matter.

How do i make total movies header to not repeat itself from RT API call in AngularJS?

Okay so I have this problem where I have to hide the total amount of movies found in a search with the rotten tomatoes api. Every time I type in a query, I get a repeat of the same header with each different movie that appears. I need to only repeat it at the top. Here is an image of what is happening since I can't do it in JSFiddle.
Here is my HTML code:
<html ng-app="demoApp">
<head>
<title>demo</title>
<script src="angular.min.js"></script>
<script src="search.js"></script>
</head>
<body ng-controller="moviesController">
<label for="q">Search Text</label>
<input type="text" id="q" ng-model="data.q" ng-model-options="{debounce: 500}"/>
<label for="page_limit">Page Size</label>
<input type="text" id="page_limit" ng-model="data.page_limit" ng-model-options="{debounce: 500}"/>
<label for="page">Page Number</label>
<input type="text" id="page" ng-model="data.page" ng-model-options="{debounce: 500}"/>
<div class="movie" ng-repeat="movie in movies">
<h1>Total movies: {{totalMovies}}</h1>
<div>
<img src="{{movie.posters.thumbnail}}" />
<h2>{{movie.title}}</h2>
</div>
<div>
<p>{{movie.synopsis}}</p>
<dl>
<dt>Rating</dt>
<dd>{{movie.mpaa_rating}}</dd>
<dt>Year</dt>
<dd>{{movie.year}}</dd>
<dt>Critics Score</dt>
<dd>{{movie.ratings.critics_score}}</dd>
<dt>Audience Score</dt>
<dd>{{movie.ratings.audience_score}}</dd>
<dt>Theater Release Date</dt>
<dd>{{movie.release_dates.theater}}</dd>
<dt>DVD Release Date</dt>
<dd>{{movie.release_dates.dvd}}</dd>
</dl>
</div>
</div>
</body>
</html>
Here is my angularJS code
angular.module('demoApp', [])
.constant('apiKey', 'removed for security')
.constant('apiUrl', 'http://api.rottentomatoes.com/api/public/v1.0/movies.json')
.controller('moviesController', function ($scope, $http, apiUrl, apiKey) {
$scope.data = {}
$scope.$watchGroup(['data.q', 'data.page_limit', 'data.page'], function () {
$http.jsonp(apiUrl, {
params: {
q: $scope.data.q,
page_limit: $scope.data.page_limit,
page: $scope.data.page,
apikey: apiKey,
callback: 'JSON_CALLBACK'
}
}).then(function (response) {
$scope.movies = response.data.movies;
//Call total movies
$scope.totalMovies = response.data.total;
});
});
});
Just check the index:
<h1 ng-if="$index == 0">Total movies: {{totalMovies}}</h1>
Move the total movie heading outside of the ngRepeat.
<h1>Total movies: {{totalMovies}}</h1>
<div class="movie" ng-repeat="movie in movies">
<!-- movie stuff -->

angular ng-submit doesnot work

I am working on a angular-js project. I want to submit a form by ng-submit. But It is not work.
My Html code is
<!DOCTYPE html>
<html lang="en">
<head>
<title>AngularJS Routes example</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
</head>
<body ng-app="sampleApp" class="container">
<div class="btn-group">
List
Add New
</div>
<hr>
<div ng-view></div>
<script>
var module = angular.module("sampleApp", ['ngRoute']);
module.config(['$routeProvider','$locationProvider',
function($routeProvider,$locationProvider) {
$routeProvider.
when('/view', {
templateUrl: 'template/view/list',
controller: 'RouteController'
}).
when('/add', {
templateUrl: 'template/view/new',
controller: 'RouteController'
}).
otherwise({
redirectTo: '/view'
});
$locationProvider.html5Mode(true);
}]);
module.controller("RouteController", function($http,$scope, $routeParams) {
$http.get('welcome/phones').success(function(data) {
$scope.phones = data;
});
$scope.formData = {};
$scope.saveInfo = function() {
formData = $scope.form;
console.log(formData);
$http.post('welcome/save',formData);
}
});
</script>
</body>
</html>
My form template is
<form action="#" ng-submit="saveInfo()" method="post" ng-controller="RouteController">
<div class="form-group">
<label for="">Product</label>
<input type="text" name="name" ng-model="form.name" class="form-control">
</div>
<div class="form-group">
<label for="">Price</label>
<input type="text" name="price" ng-model="form.price" class="form-control">
</div>
<div class="form-group">
<input type="submit" class="btn btn-info" value="Submit">
</div>
</form>
My /add,/view roure work fine. But when I submit the form, ng-submit does not work. The form submit directly. I does not get any thing in console. Where is my problem?. Thank you.
Try intializing $scope.form:
$scope.formData = {};
$scope.form = {};
module.controller("RouteController", function($http,$scope, $routeParams) {
$http.get('welcome/phones').success(function(data) {
$scope.phones = data;
});
$scope.formData = {};
$scope.form = {};
$scope.saveInfo = function() {
$scope.formData = $scope.form;
console.log( $scope.formData);
$http.post('welcome/save', $scope.formData);
}
});
Based upon the code you have submitted, you don't intend to use $scope.formData. I think its a typo you made. Just change that like to $scope.form = {}
$scope.form = {}; // instead of $scope.formData

AngularJS “Wire up a Backend” the app is not loading data on edit dialog - with latest firebase

There is another same question asked here, but the solution didn't really solve my problem even after following the instructions from it. However it works with the older version of the firebase only if I put 'OrderByPriority' in the 'ng-repeat' section.
Please help as I'm new to angular and firebase.
project.js
angular.module('project', ['ngRoute', 'firebase'])
.value('fbURL', 'https://mock-ng.firebaseio.com/')
.factory('Projects', function($firebaseArray, fbURL) {
return $firebaseArray(new Firebase(fbURL));
})
.config(function($routeProvider) {
$routeProvider
.when('/edit/:projectId', {
controller:'EditCtrl',
templateUrl:'detail.html'
})
.when('/new', {
controller:'CreateCtrl',
templateUrl:'detail.html'
})
.when('/', {
controller:'ListCtrl',
templateUrl:'list.html'
})
.otherwise({
controller:'ListCtrl',
templateUrl:'list.html'
});
})
.controller('ListCtrl', function($scope, $firebaseArray, Projects) {
$scope.projects = Projects;
})
.controller('CreateCtrl', function($scope, $location, $timeout, Projects) {
$scope.save = function() {
Projects.$add($scope.project, function() {
$timeout(function() { $location.path('/'); });
});
};
})
.controller('EditCtrl',
function($scope, $location, $routeParams, $firebaseArray, fbURL, Projects) {
var projectUrl = fbURL + $routeParams.projectId;
$scope.project = $firebaseArray(new Firebase(projectUrl));
$scope.destroy = function() {
$scope.project.$remove();
$location.path('/');
};
$scope.save = function() {
$scope.project.$save();
$location.path('/');
};
});
list.html
<input type="text" ng-model="search" class="search-query"
placeholder="Search">
<table>
<thead>
<tr>
<th>Project</th>
<th>Description</th>
<th><i class="icon-plus-sign"></i></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="project in projects | filter:search | orderBy:'name'">
<td>{{project.name}}
</td>
<td>{{project.description}}</td>
<td>
<i class="icon-pencil"></i>
</td>
</tr>
</tbody>
</table>
detail.html
<form class="form-group" name="myForm">
<div class="form-group" ng-class="{error: myForm.name.$invalid}">
<label class="control-label" for="name">Name</label>
<input type="text" class="form-control" name="name" ng-model="project.name" required>
<span class="help-block" ng-show="myForm.name.$error.required">Required</span>
</div>
<div class="form-group" ng-class="{error: myForm.site.$invalid}">
<label class="control-label" for="site">Site URL</label>
<input type="url" class="form-control" name="site" ng-model="project.site" required>
<span class="help-block" ng-show="myForm.site.$error.required">Required</span>
<span class="help-block" ng-show="myForm.site.$error.url">Not a URL</span>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" name="description" ng-model="project.description"></textarea>
</div>
Cancel
<button type="button" class="btn btn-primary" ng-click="save()" ng-disabled="myForm.$invalid">Save</button>
<button type="button" class="btn btn-danger" ng-click="destroy()" ng-show="project.$remove">Delete</button>
</form>
index.html
<!doctype html>
<html ng-app="project">
<head>
<script src="libs/jquery-1.11.3.min.js"></script>
<script src="libs/bootstrap/js/bootstrap.js"></script>
<script src="libs/angularjs/angular/angular.js"></script>
<script src="libs/firebase/firebase.js"></script>
<script src="libs/firebase/angularfire.min.js"></script>
<script src="libs/angularjs/angular-route.js"></script>
<script src="libs/datepicker/moment.js"></script>
<script src="libs/datepicker/daterangepicker.js"></script>
<script src="libs/autocomplete/select-tpls.min.js"></script>
<script src="libs/angularjs/dirPagination.js"></script>
<script src="libs/bootstrap/js/ui-bootstrap-tpls-0.12.1.min.js"></script>
<link rel="stylesheet" href="bootstrap.css">
<script src="project.js"></script>
</head>
<body>
<h2>JavaScript Projects</h2>
<div ng-view></div>
</body>
</html>
Thanks in advance!
This issue is in your EditCtrl. You're using a $firebaseArray() when you want to sync a $firebaseObject().
Plnkr Demo
.value('fbURL', 'https://mock-ng.firebaseio.com/')
// constructor injection for a Firebase database reference
.service('rootRef', ['fbURL', Firebase])
.controller('EditCtrl',
function($scope, $location, $routeParams, $firebaseObject, rootRef) {
// create the project item level reference
var projectRef = rootRef.child($routeParams.projectId)
// synchronize the project as an object, not an array
$scope.project = $firebaseObject(projectRef);
$scope.destroy = function() {
$scope.project.$remove();
$location.path('/');
};
$scope.save = function() {
$scope.project.$save();
$location.path('/');
};
});

AngularJS:Uncaught Error: [$injector:modulerr]

I'm trying AngularJS example given on http://angularjs.org titled Wire up a Backend.
I've copied code and saved files on my machine.
While executing index.html,
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.13/$injector/modulerr?p0=project&p1=Error%3…gleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.13%2Fangular.min.js%3A17%3A431)
error is displaying on console.
Any help will be appreciated.
following is the code.
index.html
<!doctype html>
<html ng-app="project">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular-resource.min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular-route.min.js">
</script>
<script src="https://cdn.firebase.com/v0/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/0.5.0/angularfire.min.js"></script>
<script src="project.js"></script>
</head>
<body>
<h2>JavaScript Projects</h2>
<div ng-view></div>
</body>
</html>
project.js
angular.module('project', ['ngRoute', 'firebase'])
.value('fbURL', 'https://angularjs-projects.firebaseio.com/')
.factory('Projects', function($firebase, fbURL) {
return $firebase(new Firebase(fbURL));
})
.config(function($routeProvider) {
$routeProvider
.when('/', {
controller:'ListCtrl',
templateUrl:'list.html'
})
.when('/edit/:projectId', {
controller:'EditCtrl',
templateUrl:'detail.html'
})
.when('/new', {
controller:'CreateCtrl',
templateUrl:'detail.html'
})
.otherwise({
redirectTo:'/'
});
})
.controller('ListCtrl', function($scope, Projects) {
$scope.projects = Projects;
})
.controller('CreateCtrl', function($scope, $location, $timeout, Projects) {
$scope.save = function() {
Projects.$add($scope.project, function() {
$timeout(function() { $location.path('/'); });
});
};
})
.controller('EditCtrl',
function($scope, $location, $routeParams, $firebase, fbURL) {
var projectUrl = fbURL + $routeParams.projectId;
$scope.project = $firebase(new Firebase(projectUrl));
$scope.destroy = function() {
$scope.project.$remove();
$location.path('/');
};
$scope.save = function() {
$scope.project.$save();
$location.path('/');
};
});
list.html
<input type="text" ng-model="search" class="search-query" placeholder="Search">
<table>
<thead>
<tr>
<th>Project</th>
<th>Description</th>
<th><i class="icon-plus-sign"></i></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="project in projects | orderByPriority | filter:search | orderBy:'name'">
<td>{{project.name}}</td>
<td>{{project.description}}</td>
<td>
<i class="icon-pencil"></i>
</td>
</tr>
</tbody>
</table>
detail.html
<form name="myForm">
<div class="control-group" ng-class="{error: myForm.name.$invalid && !myForm.name.$pristine}">
<label>Name</label>
<input type="text" name="name" ng-model="project.name" required>
<span ng-show="myForm.name.$error.required && !myForm.name.$pristine" class="help-inline">Required {{myForm.name.$pristine}}</span>
</div>
<div class="control-group" ng-class="{error: myForm.site.$invalid && !myForm.site.$pristine}">
<label>Website</label>
<input type="url" name="site" ng-model="project.site" required>
<span ng-show="myForm.site.$error.required && !myForm.name.$pristine" class="help-inline">Required</span>
<span ng-show="myForm.site.$error.url" class="help-inline">
Not a URL</span>
</div>
<label>Description</label>
<textarea name="description" ng-model="project.description"></textarea>
<br>
Cancel
<button ng-click="save()" ng-disabled="myForm.$invalid"
class="btn btn-primary">Save</button>
<button ng-click="destroy()"
ng-show="project.$remove" class="btn btn-danger">Delete</button>
</form>
I think it's wrong with your $resource instance Project, which neither been injected in module('project', ['ngRoute', 'firebase']) nor create .factory('Projects').
So you need sth like following i think:
angular.module('project', ['ngRoute', 'firebase'])
.factory('Projects', function($resource) {
return $resource('url:id',
{
id: "#id"
});
})
or create a new module and include in ['ngRoute', 'firebase']

Categories