How to dynamically insert items from a Array on one page - javascript

I would like to direct the pages of templateUrl , en route, to the wizard.html page. To filter fixed items to their respective pages , I use: | filterBy: ['href']:'/sound-waves' , for example. How could insert the items dynamically on one page ?
angular.module('tareasApp')
.controller('NatureCtrl', function ($scope, $routeParams, $sce, $location, $anchorScroll) {
$scope.items =[
{
href:'/sound-waves',
img:'waves.jpg',
video:'//www.youtube.com/watch?v=OG2eGVt6v2o',
description:'Those Relaxing Sounds of Waves'
},
{
href:'/nature-relaxing-sound',
img:'ocean.jpg',
video:'//www.youtube.com/watch?v=SWR0GdC7_40',
description:'Nature Sounds Relaxing Ocean Sounds'
}
];
});
Page wizard.html
<div ng-controller="NatureCtrl">
<div ng-repeat="item in items | filterBy: ['href']: ''" >
<img ng-src="images/{{ item.img }}" width="400" height="200" >
<p>{{item.description}}</p>
<iframe width="655" height="400" ng-src="{{ item.video }}" frameborder="0" allowfullscreen></iframe>
</div>
</div>
Route
angular.module('tareasApp')
.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/sound-waves', {
templateUrl: 'views/wizard.html',
controller: 'NatureCtrl'
})
.when('/nature-relaxing-sound', {
templateUrl: 'views/wizard.html',
controller: 'NatureCtrl'
})
.otherwise({
redirectTo: '/'
});
});
The goal is to avoid having multiple pages with the same structure.
Edited: The names of the pages are not in sequence so no . I had put to make it easier to understand . ( Had written as: page-one , page-two changed to sound-waves, nature-relaxing-sound )
Edited: Put the ...controller('NatureCtrl', function... involving the items array for better understanding.

You are right that creating a route for each URL is the wrong way to go, which is why $routeProvider supports route params.
You can define your route as follows:
$routeProvider
.when("/:pageName", {
templateUrl: "views/wizard.html",
controller: "NatureCtrl"
});
and pageName will be available as a $routeParam.pageName:
.controller("NatureCtrl", function($scope, $routeParams){
// ... pageName could be: "sound-waves" or "nature-relaxing-sound"
$scope.pageName = $routeParams.pageName;
});
If the items are coming from a service, say ItemsService, you could also use the resolve property to obtain the items and even pre-filter them as they are coming from the service, as an inject-able parameter for your controller. Here's how it could look like:
$routeProvider
.when("/:pageName", {
templateUrl: "views/wizard.html",
resolve: {
item: function(ItemService, $route){
// $routeParams here would not yet have the params for this route
return ItemsService.getItemsForPage($route.current.params.pageName);
}
},
controller: function($scope, item){
$scope.itemForThePage = item;
}
})

Related

Sending a $routeParam to the server through a service Angular

You will have to bear with me because I am a self-taught noob.
I have a php page on my server that need a $_get variable to sort the data on the server side rather than the client. I am using routeParams in Angular for the variable to send over. This works, however it only works when you refresh the webpage. Please can someone help me as my head hurts from hitting the wall.
Controller:
app.controller('JuiceController', ['$scope', 'juices', function($scope, juices) {
juices.success(function(data){
$scope.juices = data;
});
}]);
Service:
app.factory('juices', ['$http', '$routeParams',function($http, $routeParams) {
return $http.get('http://madcow-app.dev/application/backend/api/products.php', {
params: {prod: $routeParams.prod}
})
.success(function(data) {
return data;
})
.error(function(err){
return err;
});
}]);
Html output (juice view):
<div class="juice-wrap" ng-repeat="juice in juices">
<div class="juice-img"><img ng-src="{{ juice.imgpath }}" width="163" height="176" alt=""/></div>
<div class="juice-rght">
<div class="juice-title">{{ juice.name }}</div>
<div class="juice-desc">{{ juice.descrip }}</div>
Route provider
$routeProvider
.when('/', {
templateUrl: 'script/views/home.html'
})
.when('/categories/', {
controller: 'CatController',
templateUrl: 'script/views/categories.html'
})
.when('/juice/:prod', {
controller: 'JuiceController',
templateUrl: 'script/views/juice.html'
})
.when('/events/', {
controller: 'EventController',
templateUrl: 'script/views/events.html'
})
.when('/qr/', {
templateUrl: 'script/views/qr.html'
})
.when('/feedback/', {
templateUrl: 'script/views/feedback.html'
})
.otherwise({
redirectTo: '/'
php function outputs json (this is outputted to the php controller below and takes the category id as a variable:)
return json_encode($results);
To the php controller (this is the page that the angular service/factory pulls the json array of products from:
<?php
include "../../init.php";
if (isset($_GET['prod']))
{
echo $MC->Api->getProductsApi($_GET['prod']);
}
else
{
echo 'error';
}
This is the category html:
<div class="cat-btn" ng-repeat="cat in cats">
<a href="#/juice/{{cat.catid}}">
<img ng-src="{{ cat.imgpath }}" width="363" height="195" alt=""/>
<div class="cat-btn-text"> {{ cat.name }} </div>
</a>
basically what I want to achieve is when a user clicks a category in the frontend, angular routes to the product view using the category id as a filter for the php function to populate the json output with only the juices in that category.
I'm not sure if I should be doing it this way around, or whether I need to hit it from another angle. Please bear in mind that i am a complete javascript noob and laymans would be great for the answer.
Thank you in advance.....
Factory:
app.factory('juices', [
'$http', '$routeParams', function ($http, $routeParams) {
var self = this;
function getJuices() {
$http.get('http://madcow-app.dev/application/backend/api/products.php', {
params: {prod: $routeParams.prod}
})
.success(function (data) {
self.juices = data.data;
})
.error(function (err) {
});
}
return {
getJuices: getJuices,
juices: self.juices
}
}
]);
Controller:
app.controller('JuiceController', [
'$scope', 'juices', function ($scope, juices) {
juices.getJuices();
$scope.$watch(function () {
return juices.juices
}, function (newJuices, oldJuices) {
// This is triggered when juices.juices changes
// newJuices containes the juices retrieved from server
// This is needed because it is asynchronous
});
}
]);

How should I get the data from JSON into another angular js controller?

I'm new to AngularJS and stuck on below code.
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: "partials/home.html",
controller: "mainController",
})
.when('/products', {
templateUrl: "partials/productlist.html",
//controller: "ProductController",
})
.when('/product/:prodID', {
templateUrl: "partials/product.html",
controller: "viewController",
})
.when('/contact', {
templateUrl: "partials/contact.html",
controller: "contactController",
})
.otherwise({
redirectTo: "/"
});
});
app.controller('ProductController', function($scope, $http){
$http.get('partials/productTable.json').success(function(response){
$scope.datap = response.lists;
});
}).
controller('viewController',function($scope,$routeParams){
$scope.eachproduct = $scope.datap[$routeParams.prodID];
});
And my product.html page code will look like this.
<div ng-controller="viewController">
<ol class="breadcrumb">
<li>Home</li>
<li>Products</li>
<li class="active">{{eachproduct.link}}</li>
</ol>
<div class="col-md-4">
<figure><img ng-src="{{ }}"></figure>
<p>
Read More
</p>
</div>
</div>
Problem is when I navigate to any product page value of {{eachproduct.link}} is not showing.
Any solution will be appriciated.
Use $rootScope instead of $scope
$rootScope
The $rootScope is the top-most scope. An app can have only one $rootScope which will be shared among all the components of an app. Hence it acts like a global variable. All other $scopes are children of the $rootScope.
Sample :
controller('viewController',['$scope','$routeParams', '$http','$rootScope',function($scope,$routeParams, $http,$rootScope){
$http.get('partials/productTable.json').success(function(response){
$scope.datap = response.lists;
$rootScope.eachproduct = $scope.datap[$routeParams.prodID];
});
}]);
app.controller('ProductController', function($scope, $http){
$http.get('partials/productTable.json').success(function(response){
$scope.datap = response.lists;
});
}).
controller('viewController',function($scope,$routeParams, $http){
$http.get('partials/productTable.json').success(function(response){
$scope.datap = response.lists;
$scope.eachproduct = $scope.datap[$routeParams.prodID];
});
});
It seems like what you are looking for is an angular provider such as a factory to store the values in, this will allow the values to be pass values around the controllers while using the routes.
Have a look at this example, while it isn't using routes, the principal is the same:
https://jsbin.com/wiwejapiku/edit?html,js,output
For more information on providers have a look here:
https://docs.angularjs.org/guide/providers
Your example would work something like this:
app
.factory('productFactory',function(){
return {
data: {}
};
})
.controller('ProductController', function($scope, $http, productFactory){
$scope.productFactory = productFactory;
$http.get('partials/productTable.json').success(function(response){
$scope.productFactory.data = response.lists;
});
}).
controller('viewController',function($scope,$routeParams, productFactory){
$scope.productFactory = productFactory;
$scope.eachproduct = $scope.productFactory.data[$routeParams.prodID];
});
Note you would also have to change your view to reference 'productFactory.data' respectively.

How to set up two $routeParams in the same app?

I'm trying to use two $routeParams , but, appears only the templateUrl of a route. What is the best solution to be able to use $routeParams in all controllers?
Route
angular.module('tareasApp')
.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
console.log("route")
$routeProvider
//These are pages that make up the menu
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/humor', {
templateUrl: 'views/humor.html',
controller: 'HumorCtrl'
})
.when('/nature', {
templateUrl: 'views/nature.html',
controller: 'NatureCtrl'
})
// The $routeParams are to the pages of articles
// Articles in controller HumorCtrl appear perfectly
.when("/:pageName", {
templateUrl: "views/wizard-humor.html",
controller: "HumorCtrl"
})
// Articles in controller NatureCtrl no appear
.when("/:pageName", {
templateUrl: "views/wizard-nature.html",
controller: "NatureCtrl"
})
.otherwise({
redirectTo: '/'
});
});
Controller Humor
angular.module('tareasApp')
.controller('HumorCtrl', function ($scope, $routeParams, $location) {
$scope.pageName = $routeParams.pageName;
$scope.items =[
{
href:'/gold-digger',
img:'digger.jpg',
video:'//www.youtube.com/watch?v=lIruzMwBHJY',
description:'Gold Digger Camel Prank!'
},
{
href:'/woman-abused',
img:'woman.jpg',
video:'//www.youtube.com/watch?v=WXfH3mKqy0A',
description:'Woman Abused In Front Of Cops Prank!'
}
];
$scope.item = $scope.items.filter(function(item) {
return item.href.indexOf($routeParams.pageName) === 1;
})[0];
});
Controller Nature
angular.module('tareasApp')
.controller('NatureCtrl', function ($scope, $routeParams, $location) {
$scope.pageName = $routeParams.pageName;
$scope.items =[
{
href:'/sound-waves',
img:'waves.jpg',
video:'//www.youtube.com/watch?v=OG2eGVt6v2o',
description:'Those Relaxing Sounds of Waves'
},
{
href:'/nature-relaxing-sound',
img:'ocean.jpg',
video:'//www.youtube.com/watch?v=SWR0GdC7_40',
description:'Nature Sounds Relaxing Ocean Sounds'
}
];
$scope.item = $scope.items.filter(function(item) {
return item.href.indexOf($routeParams.pageName) === 1;
})[0];
});
Page wizard-humor.html
<div ng-controller="HumorCtrl">
<img ng-src="images/{{ item.img }}" width="400" height="200" >
<p>{{item.description}}</p>
<iframe width="655" height="400" ng-src="{{ item.video }}" frameborder="0" allowfullscreen></iframe>
</div>
Page wizard-nature.html
<div ng-controller="NatureCtrl">
<img ng-src="images/{{ item.img }}" width="400" height="200" >
<p>{{item.description}}</p>
<iframe width="655" height="400" ng-src="{{ item.video }}" frameborder="0" allowfullscreen></iframe>
</div>
Edited: The problem is the Subdirectory routing not working... I use html5Mode is my <base> tag are thereby <base href="/"> , how to configure correctly for subdirectories work correctly?
You've got twice exactly this same route .when("/:pageName", {..
.when("/:pageName", {
templateUrl: "views/wizard-humor.html",
controller: "HumorCtrl"
})
// Articles in controller NatureCtrl no appear
.when("/:pageName", {
templateUrl: "views/wizard-nature.html",
controller: "NatureCtrl"
})
.otherwise({
redirectTo: '/'
});
change it to :
.when("/humor/:pageName", {
templateUrl: "wizard-humor.html",
controller: "HumorCtrl"
})
// Articles in controller NatureCtrl no appear
.when("/nature/:pageName", {
templateUrl: "wizard-nature.html",
controller: "NatureCtrl"
})
and after that you can have a link like /nature/something or /humor/something
please see demo here http://plnkr.co/edit/fklkUO3YTiXaFYXuDrEz?p=preview

Can .when be dynamically generated with Angular $routeProvider?

Have an app where admins create ITEMs for users to view. Each ITEM is a doc stored in Mongo.
The item.html view and ItemController.js are consistent for all the ITEMs..
The user is first presented an ITEM_list view..
..where the user can click on an ITEM divBox,
which would reveal the item.html view populated with the specific db content found for the selected ITEM
Is there a way to have angular do something like this in appRoutes.js
angular.module('appRoutes', []).config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
// start page listing all the ITEMs
.when('/', {
templateUrl: 'views/itemsList.html',
controller: 'ItemsListController'
})
// dynamic pages for each ITEM, once selected ?!
.when('/{{ITEM}}', {
templateUrl: 'views/item.html',
controller: 'ItemController'
});
$locationProvider.html5Mode(true);
}]);
You can use parameters in the route by using a colon before whatever variable name you want.
For example:
.when('/:itemID', {
templateUrl: 'views/item.html',
controller: 'ItemController'
}
Then in your ItemController, you can call that using $routeParams.
.controller('ItemController', ['$scope', '$routeParams',
function($scope, $routeParams) {
$scope.itemID = $routeParams.itemID;
}]);
Here is the link to the Angular docs for some more guidance. http://docs.angularjs.org/tutorial/step_07
You can pass the item id, for example, like so:
.when('/item/:item_id', {
templateUrl: 'views/item.html',
controller: 'ItemController'
})
Then, in your controller, you can inject $routeParams:
.controller('ItemController', function($scope, $routeParams) {
var item_id = $routeParams.item_id;
});
Then, when they select, you set the location to /item/2 or whatever, and you know it is item 2 in your controller, so you can then either fetch that item from the server, or if you have a service with them already loaded you can figure out which one it is.

Angularjs passing parameter to a page from ng-click

I have following three buttons on top of my page with input box underneath it.
<div>
<form>
<div>
Enter Show Name<input type="text" ng-model="showName" />
</div>
</form>
</div>
<div>
<button ng-click="href="/api/renameShow"">Rename Show</button>
<button ng-click="href="/api/updateShow"">Update Show</button>
<button ng-click="href="/api/checkShow"">Check Show</button>
</div>
My module code with routes is
var showApp = angular.module("showApp", ["ngRoute", "ngResource", "ui"]).
config(function ($routeProvider, $locationProvider) {
$routeProvider.
when('/',
{
controller: '',
templateUrl: 'main.html'
}).
when('/api/renameShow', { controller: 'renameShowCtrl', templateUrl: '/templates/renameShow.html' }).
when('/api/updateShow', { controller: 'updateShowCtrl', templateUrl: '/templates/updateShow.html' }).
when('/api/checkShow', { controller: 'checkShowCtrl', templateUrl: '/templates/checkShow.html' });
Basically what I am trying to do is that when one of the buttons is clicked the ng-click calls the corrosponding page passing the parameter "showName" with it.
Please let me know how to fix it. Thanks
First of all you need to tell your destination controllers (the page you are referring to) to expect and accept a parameter when we navigate to that page:
$routeProvider.when('/api/renameShow/:showName?', {
controller: 'renameShowCtrl',
templateUrl: '/templates/renameShow.html'
})
The question mark after the parameter denotes that it's an optional parameter. You can achieve the same with anchor tags:
Go to view 2
If you insist on using buttons, write a custom function hooking onto the ng-click of the button, and then pass whatever parameter you want like this from your current controller:
<button ng-click="customNavigate('Mike')">Rename Show</button>
And in the controller:
$scope.customNavigate=function(msg){
$location.path("/view2"+msg)
}
and then in the destination controller:
app.controller("renameShowCtrl",function($scope,$routeParams){
$scope.showName=$routeParams.showName
});
Say we need psoid in sodtl.htm:
In HTML - so.html:
<tr ng-controller="SoController" ng-repeat="x in sos">
<td>{{x.date}}</td>
<td>Dtl</td>
</tr>
In AngularJs - app.js - Config:
app.config(function ($routeProvider)
{
$routeProvider.
when ('/sodtl/:psoid?',
{
templateUrl : 'pages/sodtl.html',
controller : 'SoDtlController'
}
)
});
In Controller - app.js:
app.controller('SoDtlController', function ($scope, $http, $location, $routeParams) {
$scope.message = " $routeParams.psoid = " + $routeParams.psoid;
});
Thus you can use psoid in showing data in sodtl.html page.

Categories

Resources