ngRoute not working. is there something i am doing wrong - javascript

Below is the code i am trying to execute but it is not routing to View1.
in View1 i am just looping through each element of Simplecontroller.
Please help.
<!DOCTYPE html>
<html data-ng-app="App">
<head>
<title>a</title>
</head>
<body>
<script src="Scripts/angular.min.js" type="text/javascript"></script>
<script src="Scripts/angular-route.min.js" type="text/javascript"></script>
<script type="text/javascript">
var App = angular.module('App', ['ngRoute']);
App.config(function ($routeProvider) {
$routeProvider
.when('/', { templateUrl: 'Partials/View1.htm', controller:'SimpleController' })
.when('/partial2', { templateUrl: 'Partials/View2.htm', controller: 'SimpleController' })
.otherwise({ redirectTo: '/AJTest' });
});
App.controller('SimpleController', function ($scope) {
$scope.customers =
[
{ name: 'a', city: 'a' },
{ name: 'b', city: 'b' },
{ name: 'c', city: 'c' },
{ name: 'd', city: 'd' }
];
$scope.addCustomer = function () {
$scope.customers.push({ name: $scope.newCustomer.name, city: $scope.newCustomer.city });
}
});
</script>
<div data-ng-controller="SimpleController">
Name :<br />
<input type="text" data-ng-model="name" /> {{ name }}
<ul>
<li data-ng-repeat="cust in customers | filter:name | orderBy:city">{{ cust.name + ' ' + cust.city}} </li>
</ul>
</div>
</body>
</html>
thanks in advance.

All in all the "code" you posted doesn't make sense, first of all if you wish to use ngRoute and populate views with templates, you need a ng-view somewhere, secondly the code executes SimpleController which generates the expected output in the main application, not in a view... Anyways... Here is a Plunker that does what I think your trying to do:
http://plnkr.co/edit/oVSHzzjG3SrvpNsDkvDS?p=preview
Application:
var App = angular.module('App', ['ngRoute']);
App.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'view1.html',
controller: 'View1Controller'
})
.when('/partial2', {
templateUrl: 'view2.html',
controller: 'View2Controller'
})
.otherwise({
redirectTo: '/404'
});
});
App.controller('View1Controller', function($scope) {
$scope.customers = [{
name: 'a',
city: 'a'
}, {
name: 'b',
city: 'b'
}, {
name: 'c',
city: 'c'
}, {
name: 'd',
city: 'd'
}];
$scope.addCustomer = function() {
$scope.customers.push({
name: $scope.newCustomer.name,
city: $scope.newCustomer.city
});
}
});
App.controller('View2Controller', function($scope) {
$scope.hello = "BOOOO!";
});
Main Page:
<!DOCTYPE html>
<html ng-app="App">
<body>
VIEW 1 - VIEW 2
<div ng-view></div>
<script src="https://code.angularjs.org/1.2.16/angular.min.js"></script>
<script src="https://code.angularjs.org/1.2.16/angular-route.min.js"></script>
<script src="script.js" ></script>
</body>
</html>
View1:
HELLO FROM VIEW 1:
<br />
<br />Running through items in the view::
<br />Name :
<br />
<input type="text" data-ng-model="name" />{{ name }}
<ul>
<li data-ng-repeat="cust in customers | filter:name | orderBy:city">{{ cust.name + ' ' + cust.city}}</li>
</ul>

Related

How to use same controller in different ngRoute pages

Hi I want same controller in different pages. How to pass the object to different pages. Below is my sample code.
Page1.html
<body ng-app="myapp" ng-controller="studentController">
<div>
<table border="0">
<tr>
<td>
<table>
<tr>
<th>Name</th>.
<th>Marks</th>
</tr>
<tr ng-repeat="subject in student.subjects">
<td> {{ subject.name }}</td>
<td>{{ subject.marks }}</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
<div ng-view></div>
</body>
Script.js
var app = angular.module("myapp", ["ngRoute"]);
app.config(function ($routeProvider) {
$routeProvider
.when("/Page1", {
template: '<h1>Page 1</h1>'
})
.when("/Page2", {
templateUrl: 'Page2.html',
controller: 'studentController'
})
.otherwise({
template: '<h1>note found</h1>'
})
});
app.controller('studentController', function ($scope) {
$scope.student = {
firstName: "AAA",
lastName: "ZZZ",
fees: 500,
subjects: [
{ name: 'Physics', marks: 70 },
{ name: 'Chemistry', marks: 80 },
{ name: 'Math', marks: 65 },
{ name: 'English', marks: 75 },
{ name: 'Computers', marks: 67 }
],
};
});
Page2.html
<body ng-app="myapp" ng-controller="studentController">
<h1>Hello</h1>
<h2>
subject name - {{ subject.name }}
</h2>
</body>
How to pass subject object from page 1 to page 2.
I define same controller in route config.
Is there anything do i need to define?
You can use a service for that. A service is a singleton in AngularJs, so there is only one instance of it, which makes it a perfect fit if you wanna share data over different controllers
app.service('studentService', function() {
this.student = {
firstName: "AAA",
lastName: "ZZZ",
fees: 500,
subjects: [
{ name: 'Physics', marks: 70 },
{ name: 'Chemistry', marks: 80 },
{ name: 'Math', marks: 65 },
{ name: 'English', marks: 75 },
{ name: 'Computers', marks: 67 }
],
};
this.getSubjects = function () {
return this.student.subjects;
};
});
You can then inject it in your controller(s):
app.controller('studentController', function ($scope, studentService) {
$scope.subjects = studentService.getSubjects();
});
How to pass subject object from page 1 to page 2.
Instead of passing the object, pass an index.
Use an index in the URL in the ng-repeat:
<tr ng-repeat="subject in student.subjects">
<td> {{ subject.name }}</td>
<td>{{ subject.marks }}</td>
</tr>
Define the route with an index parameter:
.when("/Page2/:index", {
templateUrl: 'Page2.html',
controller: 'subjectController'
})
Subject controller
.controller('SubjectController', function($scope, $routeParams) {
$scope.params = $routeParams;
$scope.subject = $scope.subjects[$routeParams.index];
})
Page2.html
<div>
<h1>Subject index {{params.index}}</h1>
<h2>
subject name - {{ subject.name }}
</h2>
</div>
The controller in the ng-view element will inherit the data from the controller instantioated in the main app.

angularjs filter not filter multipe filter value

Am looking for angularjs multiple condition filter like this arr in array | filter:filters.search | filter:{company: selectedName} | filter:{voucher_type: both } It working but not filtering all condition am pasting my full code here . filter:{company: selectedName} | filter:{voucher_type: both } this filter step is wrong in my code.#Thank you for response
<html >
<head>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"/>
<title>search</title>
</head>
<body>
<div ng-app="app" ng-controller="mainCtrl">
<div><select ng-model="selectedName" ng-options="x for x in names">
</select>
</div>
<input type="text" ng-model="both">
<div>Search by Name: <input type="text" ng-model="filters.search"></div>
<div ng-repeat="arr in array | filter:filters.search | filter:{company: selectedName} | filter:{voucher_type: both } ">
<span ng-bind="arr.name"></span>
</div>
</div>
<script type="text/javascript" src="js/angular.min.js"></script>
<script src="js/ui-bootstrap-tpls-0.9.0.js"></script>
<script type="text/javascript">
var app = angular.module('app', []);
app.controller('mainCtrl', function($scope) {
$scope.names = ["x", "y"];
$scope.filters = {
x: false,
company: '',
search: ''
};
$scope.actions = {
updateyCompany: function () {
if($scope.filters.y) {
$scope.filters.company = 'y';
} else {
$scope.filters.company = '';
}
}
};
$scope.both ="z";
$scope.array = [
{name: 'Tobias', lname: 'TLname', company: 'x'},
{name: 'Jeff', lname: 'JLname', company: 'x'},
{name: 'Brian', lname: 'BLname', company: 'x'},
{name: 'Igor', lname: 'ILname', company: 'y'},
{name: 'James', lname: 'JLname', company: 'z'},
{name: 'Brad', lname: 'BLname', company: 'y'},
{name: 'Basil', lname: 'Basil', company: 'z'},
];
});
</script>
</body>
</html>
Field voucher_type is not available in your array so, it can not find out. Please add this field and make filter working Properly. !!!
am make some changes it work fine now filter:valFilter filter is changed and new function is added
$scope.valFilter = function (arr) {
return (arr.company == "z" || arr.company == $scope.selectedName);
}
Thank you all

ng-options doesn't work angularjs

Factory:
(function(){
angular
.module('projectApp')
.factory('weatherfactory', weatherfactory);
weatherfactory.$inject=['$http'];
function weatherfactory($http){
var cities=[
{name: "Łódź", link: "http://api.openweathermap.org/data/2.5/forecast/daily? q=Lodz&mode=json&units=metric&cnt=7&lang=pl"},
{name: "Warszawa", link: "http://api.openweathermap.org/data/2.5/forecast/daily?q=Warszawa&mode=json&units=metric&cnt=7&lang=pl"},
{name: "Wrocław", link: "http://api.openweathermap.org/data/2.5/forecast/daily?q=Wroclaw&mode=json&units=metric&cnt=7&lang=pl"},
{name: "Kraków", link: "http://api.openweathermap.org/data/2.5/forecast/daily?q=Krakow&mode=json&units=metric&cnt=7&lang=pl"},
{name: "Gdańsk", link: "http://api.openweathermap.org/data/2.5/forecast/daily?q=Gdansk&mode=json&units=metric&cnt=7&lang=pl"},
{name: "Londyn", link: "http://api.openweathermap.org/data/2.5/forecast/daily?q=London&mode=json&units=metric&cnt=7&lang=pl"}
];
var weat={};
var service={
getCities: getCities,
GetWeather: _GetWeather
};
return service;
function _GetWeather(link){
return $http.get(link);
}
function getCities(){
return cities;
}
}
})();
In controller i get data from factory:
sa.cities=weatherfactory.getCities();
And in view i am trying to show data in but it does'n work:
<select class="form-control" ng-options="item.name as item.link for item in sa.cities"></select>
I am using controllerAs approach.
ng-options requires ng-model to be specified:
<select class="form-control" ng-model="something" ng-options="item.name as item.link for item in sa.cities"></select>
var app = angular.module('app', []);
app.controller('myController', function($scope) {
var sa = this;
sa.cities = [{
name: "Łódź",
link: "http://api.openweathermap.org/data/2.5/forecast/daily?q=Lodz&mode=json&units=metric&cnt=7&lang=pl"
}, {
name: "Warszawa",
link: "http://api.openweathermap.org/data/2.5/forecast/daily?q=Warszawa&mode=json&units=metric&cnt=7&lang=pl"
}, {
name: "Wrocław",
link: "http://api.openweathermap.org/data/2.5/forecast/daily?q=Wroclaw&mode=json&units=metric&cnt=7&lang=pl"
}, {
name: "Kraków",
link: "http://api.openweathermap.org/data/2.5/forecast/daily?q=Krakow&mode=json&units=metric&cnt=7&lang=pl"
}, {
name: "Gdańsk",
link: "http://api.openweathermap.org/data/2.5/forecast/daily?q=Gdansk&mode=json&units=metric&cnt=7&lang=pl"
}, {
name: "Londyn",
link: "http://api.openweathermap.org/data/2.5/forecast/daily?q=London&mode=json&units=metric&cnt=7&lang=pl"
}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<div ng-app='app' ng-controller='myController as sa'>
<select ng-model="selected" ng-options="item.name as item.link for item in sa.cities"></select>
</div>

AngularJS: What is wrong with this injection into my controller?

I am building up a simple task management system with AngularJS and am currently playing with it and mocking the data up. I have a problem with the injection of a service into my ProjectCtrl controller and I cannot wrap my head around it.
At the bottom of this code: Why is the projects variable in the ProjectsCtrl controller just an empty array? It should contain the mockup data, no? What am I doing wrong?
Please excuse this maybe very stupid question. I just don't find my mistake.
angular.module("TaskManager", ['ui.router'])
.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider){
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl'
})
.state('projects', {
url: '/projects/{id}',
templateUrl: '/projects.html',
controller: 'ProjectsCtrl'
});
$urlRouterProvider.otherwise('home');
}
])
.factory('projects', [function(){
var o = {
projects: []
};
return o;
}])
.controller('MainCtrl', [
'$scope',
'projects',
function($scope, projects){
$scope.projects = projects.projects;
$scope.projects = [
{title: "project 1", done: 0},
{title: "Another project 2", done: 0},
{title: "project 3", done: 1},
{title: "project 4", done: 0},
{title: "project 5", done: 0},
];
$scope.addproject = function() {
if(!$scope.title || $scope.title === '') { return };
$scope.projects.push({
title: $scope.title,
comment: $scope.comment,
done: 0,
tasks: [
{title: 'Task 1', comment: 'Kommentar 1', done: 0},
{title: 'Task 2', comment: 'Kommentar 2', done: 0}
]
});
$scope.title = "";
$scope.comment = "";
}
$scope.markAsDone = function(project) {
project.done = 1;
}
}
])
.controller('ProjectsCtrl', [
'$scope',
'$stateParams',
'projects',
function($scope, $stateParams, projects){
$scope.project = projects.projects[$stateParams.id];
// Why is this an empty array?
console.log(projects);
}
])
For completion: This is the HTML part:
<html>
<head>
<title>TaskManager</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="TaskManager">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<ui-view></ui-view>
</div>
</div>
<script type="text/ng-template" id="/home.html">
<div class="page-header">
<h1>TaskManager</h1>
TEST
</div>
<div ng-repeat="project in projects | orderBy: ['done','title']">
<span ng-click="markAsDone(project)">Done</span>
{{project.title}} - done: {{project.done}}
<span>
Tasks
</span>
<p ng-show="project.comment">Comment: {{project.comment}}</p>
</div>
</hr>
<form ng-submit="addproject()" style="margin-top: 30px;">
<h3>Add new project</h3>
<input type="text" ng-model="title" placeholder="project"></input>
<br><br>
<textarea name="comment" ng-model="comment"></textarea>
<br>
<button type="submit" class="btn">Post</button>
</form>
</script>
<script type="text/ng-template" id="/projects.html">
<div class="page-header">
<h3>Project: {{project.title}}</h3>
</div>
<div ng-repeat="task in project.tasks | orderBy: ['done','title']">
{{task.title}} - done: {{task.done}}
<p ng-show="task.comment">Comment: {{task.comment}}</p>
</div>
</script>
</body>
</html>
You never assign the values to projects.projects. In MainCtrl, you assign $scope.projects to the value of projects.projects (which is an empty array at that point). Then after that you overwrite $scope.projects with a totally new and different array, so you never end up modifying projects.projects.
I would move functions that let you add, remove, update items to projects service, but in the interim you can assign projects.projects first and then assign that to $scope.projects.
Better projects service:
.factory('projects', function() {
var projects = [];
return {
add: function(item) {
// your additional code
projects.push(item);
},
remove: function(item) {
// your additional code
var i = projects.indexOf(item);
if (i >=0) projects.splice(i,1);
},
get: function() {
return projects;
},
initialize: function(items) {
projects = items;
}
};
});
Then you can use this in your controller:
.controller('MainCtrl', function($scope, projects) {
projects.initialize([ ... ]);
$scope.projects = projects.get();
$scope.addproject = function() {
// NOTE: move whatever code you feel is or could be the responsibility of the service to the add method. I left this function as-is though, so you have a frame of reference.
if(!$scope.title || $scope.title === '') { return };
projects.add({
title: $scope.title,
comment: $scope.comment,
done: 0,
tasks: [
{title: 'Task 1', comment: 'Kommentar 1', done: 0},
{title: 'Task 2', comment: 'Kommentar 2', done: 0}
]
});
$scope.title = "";
$scope.comment = "";
};
// etc.
});
I recommend making the service the single point of authority so you can test logic pertaining to interacting with the service and its data, and avoid repeating yourself when different controllers and directives need to interact with the service or its data. It'll also help you avoid these sorts of issues where the data becomes out of sync between different controllers, directives, etc.
When you're setting up the mock data, you're only setting them on $scope.projects...the factory's projects is never updated. You could flip it around and it should work:
projects.projects = [<mock data>];
$scope.projects = projects.projects;
Put your mocked data in factory and remove the initialization in your controller.
angular.module("TaskManager", ['ui.router'])
.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider){
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl'
})
.state('projects', {
url: '/projects/{id}',
templateUrl: '/projects.html',
controller: 'ProjectsCtrl'
});
$urlRouterProvider.otherwise('home');
}
])
.factory('projects', [function(){
var o = {
projects: [
{title: "project 1", done: 0},
{title: "Another project 2", done: 0},
{title: "project 3", done: 1},
{title: "project 4", done: 0},
{title: "project 5", done: 0},
]
};
return o;
}])
.controller('MainCtrl', [
'$scope',
'projects',
function($scope, projects){
$scope.projects = projects.projects;
$scope.addproject = function() {
if(!$scope.title || $scope.title === '') { return };
$scope.projects.push({
title: $scope.title,
comment: $scope.comment,
done: 0,
tasks: [
{title: 'Task 1', comment: 'Kommentar 1', done: 0},
{title: 'Task 2', comment: 'Kommentar 2', done: 0}
]
});
$scope.title = "";
$scope.comment = "";
}
$scope.markAsDone = function(project) {
project.done = 1;
}
}
])
.controller('ProjectsCtrl', [
'$scope',
'$stateParams',
'projects',
function($scope, $stateParams, projects){
$scope.project = projects.projects[$stateParams.id];
// Why is this an empty array?
console.log(projects);
}
])

AngularJS: What is wrong with this code snippet?

I am reading an AngularJS book. I copied the following code from the book:
<!DOCTYPE html>
<html ng-app='myApp'>
<head>
<title>Your Shopping Cart</title>
</head>
<body ng-controller='CartController'>
<h1>Your Order</h1>
<div ng-repeat='item in items'>
<span>{{item.title}}</span>
<input ng-model='item.quantity'>
<span>{{item.price | currency}}</span>
<span>{{item.price * item.quantity | currency}}</span>
<button ng-click="remove($index)">Remove</button>
</div>
<script src="js/lib/angular.min.js"></script>
<script>
function CartController($scope) {
$scope.items = [
{title: 'Paint pots', quantity: 8, price: 3.95},
{title: 'Polka dots', quantity: 17, price: 12.95},
{title: 'Pebbles', quantity: 5, price: 6.95}
];
$scope.remove = function(index) {
$scope.items.splice(index, 1);
}
}
</script>
</body>
</html>
I have the angular.min.js in place. However, I got this output from Chrome:
Apparently, there is something wrong with the code. However, as a newbie, I cannot tell where it is. Your help is greatly appreciated. Thank you very much.
update
Here is the error output:
Failed to instantiate module myApp due to:
Error: [$injector:nomod] http://errors.angularjs.org/1.2.10/$injector/nomod?p0=myApp
at Error (native)
at http://localhost:63342/angular-book/js/lib/angular.min.js:6:450
at http://localhost:63342/angular-book/js/lib/angular.min.js:20:260
at http://localhost:63342/angular-book/js/lib/angular.min.js:21:262
at http://localhost:63342/angular-book/js/lib/angular.min.js:29:175
at Array.forEach (native)
at q (http://localhost:63342/angular-book/js/lib/angular.min.js:7:280)
at e (http://localhost:63342/angular-book/js/lib/angular.min.js:29:115)
at $b (http://localhost:63342/angular-book/js/lib/angular.min.js:32:232)
at Zb.c (http://localhost:63342/angular-book/js/lib/angular.min.js:17:431
You must register the CartController with your app "myApp"
One way to do it:
angular.module('myApp').controller('CartController',['$scope', function ($scope) {
$scope.items = [
{title: 'Paint pots', quantity: 8, price: 3.95},
{title: 'Polka dots', quantity: 17, price: 12.95},
{title: 'Pebbles', quantity: 5, price: 6.95}
];
$scope.remove = function(index) {
$scope.items.splice(index, 1);
}
}]);
The AngularJS book from O'Reilly has lots of errors in it. You will have to fix lots of the code samples.
At the top of your app, you reference the name of the app, but don't register it.
<html ng-app='myApp'>
If you give a value here, you have to define the module.
angular.module('myApp', []);
You can also can assign the module to a variable for easy reference when you create controllers, etc:
var myApp = angular.module('myApp', []);
myApp.controller('myController',
function myController($scope){
};
But for a simple angular app using just one page of code, the easiest solution for your code is to just not assign a value to the ng-app attribute:
<html ng-app>
My complete working code for this example was:
<!doctype html>
<html ng-app>
<head>
<meta charset="utf-8">
<title>Your Shopping Cart</title>
</head>
<body ng-controller='CartController'>
<h1>Your Order</h1>
<div ng-repeat='item in items'>
<span>{{item.title}}</span>
<input ng-model='item.quantity'>
<span>{{item.price | currency}}</span>
<span>{{item.price * item.quantity | currency}}</span>
<button ng-click="remove($index)">Remove</button>
</div>
<script src="js/angular.min.js"></script>
<script>
function CartController($scope) {
$scope.items = [
{title: 'Paint pots', quantity: 8, price: 3.95},
{title: 'Polka dots', quantity: 17, price: 12.95},
{title: 'Pebbles', quantity: 5, price: 6.95}
];
$scope.remove = function(index) {
$scope.items.splice(index, 1);
}
}
</script>
</body>
</html>
As Luke mentioned, you must define myApp somewhere. Dependencies (controllers, directives, etc) should be injected there:
angular.module('myApp', [
// myApp dependencies (controllers, etc.) injected here...
'myApp.controllers'
]).
config(['$routeProvider', function($routeProvider) {
// your routes here...
}]);
Then you have your controller, which is what gets injected...
angular.module('myApp.controllers', []).
controller('MyCtrl', [function() {
}]);
If you haven't already, take a look at the Angular seed project. This is an outstanding resource for anyone ramping up with Angular.

Categories