Angular template pages - javascript

I want to have template site in AngularJs with /example/car/id where in different ids is a page for different cars .
In app.js i wrote :
angular
.module('carApp', [
'ngCookies',
'ngResource',
'ngRoute',
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/car/:id', {
templateUrl: 'views/car.html',
controller: 'CarCtrl'
})
});
In Json i made 2 cars:
[{
"model": "Audi",
"year": "1999"
}
{
"model": "BMW",
"year": "2005"
}]
In car.js
angular.module('carApp')
.controller('CarCtrl', ['$scope','$http', function($scope, $http)
{
$http.get('scripts/controllers/cars.json').success (function(data){
$scope.cars = data;
});
}]
);
Where and what code I need to write to have templates where in example/car/1 will show details about Audi and example/car/2 will show details about BMW ?

You can read the param using $routeParams and put them as a query string to your URL or use this version on $http :
$http({
url: user.details_path,
method: "GET",
params: {user_id: user.id}
});
https://stackoverflow.com/a/13760360/20126

Assuming you would have some sort of table or list displaying the car for the user to select you could have something like
<div ng-controller="carCtrl">
<ul ng-repeat = "car in cars">
<li> <a href ="#/cars/{{car.model}}> {{car.model}} </a></li>
</ul>
</div>
So this will create a list of cars that the user can select. On clicking on the link it will go to page on that model. (Note I am not using id here because you dont have id in you json)

I've changed the CarCrl to look like this :
angular.module('motoApp')
.controller('CarCtrl', ['$scope','$http', '$routeParams', function($scope, $http,
$routeParams) {
$http.get('scripts/controllers/cars.json').success (function(data){
$scope.car = data[$routeParams.id];
});
}]
);
And changed the JSON to dictionary :
{
"1": {
"model": "Audi",
"year": "2012",
"2": {
"model": "BMW",
"year": "2012",
}
}
and that is what i wanted to achive. Now in html i have :
<p>{{ car.model }}</p>
<p>{{ car.year }}</p>
and when i visit /car/1 it shows details about Audi and in /car/2 there is BMW

Related

ngRepeat iterate with array objects in angularjs

I'm trying to figure out on how to iterate the array using ngrepeat
If I have a array of data like below
{
"People": [{
"name": "Andrew Amernante",
"rating": 3,
},
{
"name": "Frank Wang",
"rating": 5,
},
{
"name": "Chang Wang",
"rating": 5,
}
]
}
In Controller, I have these code snippets.
app.controller('mainController', function($scope, $http) {
$http.get('people.json').
then(function onSuccess(response) {
console.log(response);
$scope.peoples = response.data;
}).
catch(function onError(response) {
console.log(response);
});
});
And, I wanted to iterate the array and display the three name in list.
<ul class="nav">
<li ng-repeat="obj.peoples track by $index">
{{obj.name}}
</li>
</ul>
But, I cannot able to get the names, any idea on this?
FYI - I'm using Angular 1.6.5 version here.
Plunkr Code here
You need to fix your HTML code.
Instead of ng-repeat="obj.peoples track by $index" it should be ng-repeat="obj in peoples.People track by $index"
See below demo.
angular.module('app', [])
.controller('mainController', function($scope, $http) {
// mocked, equivalente to `$scope.peoples = response.data`
$scope.peoples = {
"People": [{
"name": "Andrew Amernante",
"rating": 3,
},
{
"name": "Frank Wang",
"rating": 5,
},
{
"name": "Chang Wang",
"rating": 5,
}
]
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app' ng-controller='mainController'>
<ul class="nav">
<li ng-repeat="obj in peoples.People track by $index">
{{obj.name}}
</li>
</ul>
</div>
it is peoples in your script.js and you are using obj in html
$http.get('people.json').
then(function onSuccess(response) {
console.log(response);
$scope.peoples = response.data;
}).
change your html to the below code,
<li class="active" ng-repeat="item in peoples.People">
{{item.name}}<span class="glyphicon glyphicon-play"></span>
</li>
Two things, in javscript
$scope.peoples = response.data.People;
and in ng-repeat it should be
ng-repeat="people in peoples track by $index"

angular ng-repeat displaying object items

I am having a problem with displaying a JSON array objects that I have gotten from a async http request.
I have used ng-repeat to try and display the objects in the view but I am having no luck after many hours. Here is the code I have so far.
index.html
<div class="main" ng-controller = "MyController">
<ul>
<li ng-repeat="item in parks">
<div class="info">
<h2>{{item.parks.name}}<h2>
<h2>{{item.parks.park_size}}<h2>
<h2>{{item.parks.open_times}}<h2>
<h2>{{item.parks.days_closed}}<h2>
<img ng-src="images/{{item.parks.short}}.jpg">
</div>
</li>
controllers.js
var myApp = angular.module('myApp', []);
myApp.controller('MyController', ['$scope', '$http', function($scope, $http) {
$http.get('js/data.json').success(function(data) {
$scope.parks = data;
console.log(data);
});
}]);
data.json
{
"parks": [
{
"park_name": "Central Park",
"park_size": {
"miles": "1.2",
"meters": "1900"
},
"open_times": {
"Monday-Friday": "8am-10pm",
"Saturday-Sunday": "10am-6.30pm"
},
"days_closed": [
"December 25th",
"December 26th"
],
"images": [
{
"short": "centralimage1.jpeg"
},
{
"short": "centralimage2.jpeg"
},
{
"short": "centralimage3.jpeg"
},
{
"short": "centralimage4.jpeg"
}
]
},
{
"park_name": "Riverside Park",
"park_size": {
"miles": "0.2",
"meters": "320"
},
"open_times": {
"Monday-Friday": "7am-9pm",
"Saturday-Sunday": "9am-8.30pm"
},
"days_closed": [
"December 25th",
"December 26th",
"Jamuary 1st"
],
"images": [
{
"short": "riversideimage1.jpeg"
},
{
"short": "riversideimage2.jpeg"
},
{
"short": "riversideimage3.jpeg"
},
{
"short": "riversideimage4.jpeg"
}
]
}
]
}
JS fiddle
https://jsfiddle.net/owxwh0kz/
You are iterating over parks already, so your code can look like this
<li ng-repeat="item in parks">
<div class="info">
<h2>{{item.park_name}}<h2>
(I changed item.park.name to be item.park_name to match your data)
Otherwise check using the Angular inspector to see what the data looks like.
It looks like the data coming back from the json object is not consitent with your binding selectors. Inside an ng-repeat you are alreading interating over the scope of parks.
<li ng-repeat="item in parks">
<div class="info">
<h2>{{item.park_name}}<h2>
<h2>{{item.park_size}}<h2>
<h2>{{item.open_times}}<h2>
<h2>{{item.days_closed}}<h2>
For the images because they are in another array you would have to performn another repeat to grab all images.Note that nested ng-repeats can lead to negative performance impacts.
Based on your code, you should iterate over parks.parks to reach the array of the $scope.parks object.
Also, within the ng-repeat you should use item.* instead of item.parks.*
Here is JSFiddle with the fixed code: https://jsfiddle.net/x0ja420L/
Some code changes has been made in your code :
Proper closing of the HTML tags to work it properly.
Use <h2>{{item.park_name}}</h2> instead of <h2>{{item.park_name}}<h2>
ng-repeat directive iterate the array object so if you want to access park_name you have to use ng-repeat like this ng-repeat="item in parks.parks"
demo !
ng-repeat directive iterate the array object, so if you want to access park_name you have to use ng-repeat like this ng-repeat="item in parks.parks",code should like this
<li ng-repeat="item in parks.parks">
<div class="info">
<h2>{{item.park_name}}<h2>
<h2>{{item.park_size}}<h2>
<h2>{{item.open_times}}<h2>
<h2>{{item.days_closed}}<h2>
<img ng-src="images/{{item.images[0].short}}.jpg">
</div>
</li>
you can see the demo

angularjs ng-repeat drop down menu from json nested

I have the following example.json file:
[
{
"interests": [
{
"item": "art"
},
{
"item": "literature"
},
{
"item": "history"
},
{
"item": "science"
}
]
},
{
"experience": [
{
"year": "novice"
},
{
"year": "experienced"
}
]
}
]
and in my view controller, I read the file like this:
app.controller('ProfileCtrl', ["$scope", "$state", "$http",
function ($scope, $state, $http) {
$http.get('files/example.json').success(function (data)
{
$scope.myjsonobj= data;
});
and in my html view, I am injecting the values like this:
<div ng-controller="ProfileCtrl">
...
<select class="form-control" ng-model="user.favs">
<option ng-repeat="p in interests.myjsonobj" value="{{p.item}}">{{p.item}}</option>
</select>
question:
How can I show only the list of values of "interests" in my dropdown menu? How can I access the nested json array in angularjs?
my current setup is not working.
assuming 'interests' is your controller shortname.
you can use:
<option ng-repeat="p in myjsonobj[0].interests" value="{{p.item}}">{{p.item}}</option>
Ideally, you should loop the data object to find the index with the 'interests' key vs hardcoding [0].
update: removed "interests." from the repeat. doesn't seem like you have the ctrl shortname binding.
I'm not an angular guy. But with my javascript knowledge it seems to me that the
"interests.myjsonobj"
should be
"myjsonobj.interests"

Angular: Using filter in controller to set an object

I have this example of a json with many records but let's assume name is unique. I want to just filter out an object by name in the controller so my html don't have to iterate through all the records using ng-repeat all the time.
{
"records": [
{
"Name" : "Alfreds Futterkiste",
"City" : "Berlin",
"Country" : "Germany"
},
{
"Name" : "Berglunds snabbköp",
"City" : "Luleå",
"Country" : "Sweden"
},
{
"Name" : "Centro comercial Moctezuma",
"City" : "México D.F.",
"Country" : "Mexico"
}
]
}
Ideally within my html I can use the filtered object like this:
<p> {{ filteredObj.Name}} </p>
My controller looks like this. The line where I am applying the filter is not working and I can't spot the reason.
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', ['$scope', '$http', function($scope, $http) {
$http.get('customers.json').success(function (data) {
//This is where I am doing it wrong when I try to filter out the object I need
$scope.filteredObj = $filter('filter')(data.records, {name: "Alfreds Futterkiste");
});
}]);
How can I use the $filter function correctly in the controller?
You need to inject $filter.
Also $filter returns an array so you need to pick the first element (ideally you should be checking if there are any results as well).
And lastly the 2nd parameter to the filter should have Name (instead of name)
So you'd finally have something like this
myApp.controller('myCtrl', ['$scope', '$http','$filter', function ($scope, $http, $filter) {
$http.get('customers.json').success(function (data) {
//This is where I am doing it wrong when I try to filter out the object I need
$scope.filteredObj = $filter('filter')(data.records, { Name: "Alfreds Futterkiste" })[0];
});
}]);

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);
}
])

Categories