How to add links in angular js with dynamic output - javascript

I have page say categories here I'm loading categories from my api request
on clicking first category I need to load some other page say products and need to load products from some other api.
When I am linking it with simple href it displays
{{ product.productname }}
MyController page :
var app = angular.module('myApp', []);
app.controller('CategoryController', function($scope, $http) {
$http.get("http://192.168.1.112/estore/api/get-categories")
.success(function(response) {$scope.categories = response.categories;});
});
app.controller('ProductController', function($scope, $http) {
$scope.id = 2;
$http.get("http://192.168.1.112/estore/api/get-products?id=id")
.success(function(response) {$scope.products = response.categories;});
});
My index page :
<body ng-app="myApp">
<div role="main" class="ui-content" ng-controller="CategoryController">
<ul class="cat" ng-repeat="x in categories">
<li>
{{ x.name }}
</li>
</ul>
</div>
</body>
my listpage :
<body ng-app="myApp">
<div role="main" class="ui-content" ng-controller="ProductController">
<ul class="cat" ng-repeat="pdts in products">
<li>
{{ pdts.productname }}
</li>
</ul>
</div>
</body>

There are two options:-
1) you can use $state.go() and pass id parameters to products state.
2) you can use $cookiestore and set the id in the cookie and later retrieve in the products state.
var app = angular.module('myApp', []);
app.config(['$stateProvider',function($stateProvider){
$stateProvider.state('products',{
url: '/products/:ID',
title: 'productlist',
templateUrl: 'app/views/product/productlist.html',
controller:'productlistController'
})
}]);
app.controller('CategoryController', function($scope, $http ,$state) {
$http.get("http://192.168.1.112/estore/api/get-categories")
.success(function(response){
$scope.categories = response.categories;
});
$scope.redirectTo = function(id){
$state.go('products', {ID : id});
};
});
app.controller('ProductController', function($scope, $http , $state) {
var id = $state.params.ID;
$http.get("http://192.168.1.112/estore/api/get-products?id="+id)
.success(function(response) {
$scope.products = response.products;
});
});
INDEX PAGE
<body ng-app="myApp">
<div role="main" class="ui-content" ng-controller="CategoryController">
<ul class="cat" ng-repeat="x in categories">
<li>
<a ng-click="redirectTo(x.id)"> {{ x.name }} </a>
</li>
</ul>
</div>
</body>

Related

Why my $scope is not accessible in my controller - Angular JS?

I am not able to get declared scope variable in my controller. Instead I'm getting reference error : message is not defined
Below is my code:
My Index.html
<body ng-app="myApp" ng-controller="homingController" ng-cloak>
<script type="text/javascript">
angular.module('myApp' ['ngRoute','ngMaterial']).controller('homingController', ['$scope',
function($scope){
$scope.message = 'Hello';
}
]).config(function ($routeProvider) {
$routeProvider.when("/home", {
templateUrl: "home.html",
controller: "homingController"
}).when("/monitor", {
templateUrl: "monitor.html",
controller: "monitoringController"
}).otherwise({
redirectTo: '/home'
});
}).controller('monitoringController', function ($scope) {
$scope.message = "Monitor";
});
</script>
<nav class = "navbar navbar-inverse" role="navigation">
<ul class = "nav navbar-nav" >
<li ><img src="./images/home.svg">Home</li>
<li >Monitor</li>
<li ><a class = "active" ui-sref = "Audit" ><img src="./images/audit.svg">Audit</a></li>
<li ><a class = "active" ui-sref = "configuration" ><img src="./images/configure.svg">Configure</a></li>
</ul>
</nav>
</div>
</body>
<div ng-view></div>
My home.html
{{ message}}
/*This line giving error in console : angular.js:14328 ReferenceError: $scope is not defined
*/
Is there anything I am missing here?
Your <div ng-view></div> should be inside your <body> tag. By placing it outside of the body, in which you define your app, the views have no idea what app or controller they should be using.
You also don't need to identify ng-controller's anywhere around your views, since you define them in your routeconfig:
var app = angular.module('myApp' ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when("/home", {
templateUrl: "home.html",
controller: "homingController"
}).when("/monitor", {
templateUrl: "monitor.html",
controller: "monitoringController"
}).otherwise({
redirectTo: '/home'
});
});
app.controller('homingController', function($scope) {
$scope.message = 'Hello';
})
app.controller('monitoringController', function($scope) {
$scope.message = "Monitor";
});
If you want to display something from one of your controllers you should define it like so:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="homingController">
{{message}}
</div>
<nav class="navbar navbar-inverse" role="navigation">
<ul class="nav navbar-nav">
<li>
Home
</li>
<li>
Monitor
</li>
</ul>
</nav>
<div ng-view></div>
</body>
With your home.html & monitor.html containing {{ message }}. An exact example of this can be found at w3Schools (Under the heading "Controllers"). Build that, then once you have that working start expanding on it to fill in the rest of your application.

angular display ng-repeat only after clicking a button

I have a controller that runs with the page load. I would like to change it, so only after clicking a button the function will called and the results will be displayed.
HTML:
<div ng-controller="MyController">Files on server: {{ mydata }}
</div>
<ul ng-controller="MyController as controller">
<li ng-repeat="data in controller.mydata">{{ data }}</li>
</ul>
JS:
app.controller('MyController', function($http) {
var vm = this;
vm.mydata = [];
$http.get('list')
.then(function(result) {
console.log(result);
vm.mydata = result.data;
});
});
i think you need to put your http call in some function activated onclik
HTML:
<div ng-controller="MyController as controller">
<ul>
<li ng-repeat="data in controller.mydata">{{ data }}</li>
</ul>
<button ng-click="controller.getData()">get data</button>
</div>
controller:
app.controller('MyController', function($http) {
var vm = this;
vm.mydata = [];
//http call is in the 'getData' function
vm.getData = function(){
$http.get('list')
.then(function(result) {
console.log(result);
vm.mydata = result.data;
});
}
Like that :
HTML
<div ng-controller="MyController">Files on server: {{ mydata }}
</div>
<input type="button" value="Click" id="refresh"/>
<ul ng-controller="MyController as controller">
<li ng-repeat="data in controller.mydata">{{ data }}</li>
</ul>
Java script
app.controller('MyController', function ($http) {
var vm = this;
vm.mydata = [];
vm.refresh = function () {
$http.get('list')
.then(function (result) {
console.log(result);
vm.mydata = result.data;
});
};
});
Use ng-click with a button to define a function to be called on click and call your $http.get inside that function.
<button ng-click="myFunction()">Click</button>
And in your controller
vm.myFunction = function() {
$http.get('list').then(function(result) {
console.log(result);
vm.mydata = result.data;
});
});
You could simply toggle the visibility. That way you can load the data upfront and show it when you want to.
<ul ng-if="!controller.hide">
<li ng-repeat="data in controller.mydata">{{ data }}</li>
</ul>
<button ng-click="controller.hide=false">Show Me!</button>
I removed the ng-controller directive from your ul. I would put that on a higher level element that wraps all of the other elements.
It´s better to make only one call to the server, so you could get the data from the beginning.
You could toggle the visibility instead of making an api call.
<ul ng-controller="MyController as controller">
<a href="#" ng-click="controller.display == !controller.display">
Toggle Info
</a>
<li ng-if="controller.display" ng-repeat="data in controller.mydata">{{ data }}</li>
</ul>
And decelerate the display as:
vm.display = false;
Why the negation?
With that the a tag will toggle the visibility of the li elements.

Compile error for Angular JS with js/ajax.js and index.html

When I compile my code there is an error with angular.
The code is written from a book, and it works when I load the page using the code at the end of the question.
There seems to be two issues from what I have read. Where do I put the $scope and $compile code?
Mostly, the question is how do I load a document ready trigger with a button for angular JS?
Or should I always load the angular js and hide the code?
<div id="myTabs">
<div class="menu">
<ul class= "tabs">
<li >LIST</li>
<li >GRID</li>
<li >GRID</li>
</ul>
</div>
<div class="container" style="margin-top:100px">
<div id="a">
</div>
<div id="b">
<ul class="gallery-items" id="grid">
</ul>
</div>
<div id="c" >
<div ng-controller="myController">
<div ng-repeat="item in items">
<img ng-src="{{item.img}}" />
{{item.description}}<br>
Rating: {{item.rating}} stars<br>
<span ng-repeat="idx in stars"
ng-class=
"{true: 'star', false: 'empty'}[idx <= item.rating]"
ng-click="adjustRating(item, idx)">
</span>
<hr>
</div>
</div>
</div>
</div>
ajax.js has a function that calls the #c tab to load
$(document).ready(function(){
$('#listC').click(function(){
angular.module('myApp', [])
.controller('myController', ['$scope', function($scope) {
$scope.stars = [1,2,3,4,5];
$scope.items = [100];
$.ajax({
type:'post',
url:'changeView.php',
data:{action: 'getGrid'},
success:function(data){
var data = JSON.parse(data);
for (i=0;i<data.length;i++) {
var imageLI = makeImage(data[i]['imageID'], data[i]['name'], data[i]['desc']);
$scope.items[i] = imageLI;
}
}
});
console.log($scope.items);
$scope.adjustRating = function(item, value){
item.rating = value;
};
}]);
});
$('#listC').trigger('click');
function makeImage(ID, name, description){
var image = {
description: description,
img: '../uploads/'+name,
rating: 4
}
return image;

Send data one page to another pager according to ID in Angular JS

I am using mobile angular js UI frame work. I am new in angular js and want to send data one page to another page with city id. If user click on city then data show according to city.
HOME PAGE:
HTML PAGE:
<div class="jumbtron scrollable-content text-center bg-color">
<div class="row">
<div class="bgImage">
<div class="bannerCntnt">
<div class="hp-text-bnnr" style="color:white"> WHERE DO YOU WANT DELIVERY? <br>CHOOSE CITY </div> <br>
<div class="btn-group" ng-controller="MyController">
<button ui-turn-on='myDropdown' class='btn' ng-click="getDataFromServer()"
style="width:160px;background-color:white; color:#c62222">
<span class="fa fa-location-arrow"></span>
<strong>
Select City
</strong>
</button>
<ul class="dropdown-menu scrollableMenu" role="menu" ui-outer-click="Ui.turnOff('myDropdown')" ui-outer-click-if="Ui.active('myDropdown')" role="menu"
ui-show="myDropdown" ui-state="myDropdown" ui-turn-off="myDropdown" style="margin-top:0 px;margin-top:-1px; text-align:center;height:300px; overflow: scroll;">
<li ng-repeat="city in cities">
<a ng-href="#/cityPage" style="color:#763428; font-weight:bold;">{{ city.cityName }}</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
HOME PAGE CONTROLLER:
.controller('MyController' ,function ($scope, $http) {
$scope.getDataFromServer = function() {
$http({
method : 'GET',
url : 'http://192.168.0.3/sf/app/cityName',
headers: {'Content-Type': 'application/json'},
}).success(function(data, status, headers, config) {
$scope.cities = data;
$scope.cities.forEach(function(product) { Console.log(product.cityId);
});
}).error(function(data, status, headers, config) {
})
}
})
When user click on any select city from dropdown then all city id will come in console. After click on dropdown city next page will come.
SCREEN SHOT:
HTML CODE:
<div class="jumbtron scrollable-content text-center bg-color">
<div class="row">
<div class="bgImage">
</div>
<div class="btn-group img-responsive" ng-controller="MyControllerCity">
<div ng-repeat="prdct in cityProduct">
<a href="#/category-prduct" style="color:#763428; font-weight:bold;">
<img src="{{prdct.categoryImage}}">
</a>
</div>
</div>
</div>
</div>
CONTROLLER:
.controller('MyControllerCity',function($scope, $http){
$http({
method:'get',
url:'http://192.168.0.3/sf/app/city-home/1',
headers: {'Content-Type': 'application/json'},
}).success(function(data, status,headers, config) {
$scope.cityProduct = data;
$scope.cityProduct.forEach(function(product) {
console.log(product.categoryId);
console.log("--------------------------");
});
console.log("All ID"+$scope.cityProduct[0].categoryId);
}).error(function(data, status, headers ,config) {
})
})
You can see which city have how many product by this URL:
> https://www.winni.in/app/city-home/12
> https://www.winni.in/app/city-home/1
> https://www.winni.in/app/city-home/2
APP.JS
angular.module('Y', [
'ngRoute',
'mobile-angular-ui',
'Y.controllers.Main'
])
.config(function($routeProvider) {
$routeProvider.when('/', {templateUrl:'home.html', reloadOnSearch: false})
.when('/cityPage', {templateUrl:'cityPage.html', reloadOnSearch: false})
.when('/category-prduct', {templateUrl:'category-prduct.html', reloadOnSearch: false})
.when('/product-description', {templateUrl:'product-description.html', reloadOnSearch: false})
.when('/my-winni', {templateUrl:'my-winni.html', reloadOnSearch: false})
.when('/gift-box', {templateUrl:'gift-box.html', reloadOnSearch: false});
});
I want to show data in next page according to city ID.
We can find the city ID from this url
http://www.winnni.in/app/cityName
And append on this url:
https://www.winni.in/app/city-home/12
You have use routeParam for that in route file as like I do in following code, and have to get passed param in other controller via $routeParam. Here is an example:
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
</head>
<body>
<div ng-view></div>
<script>
var app = angular.module('myApp', []);
app.config(['$routeProvider',
function($routeProvider)
{
$routeProvider.
when('/city',
{
templateUrl: 'city.html',
controller: 'cityController'
}).
when('/city/:city_id',
{
templateUrl: 'city_id.html',
controller: 'CityIdController'
}).
otherwise({
redirectTo: '/'
});
}]);
app.controller('cityController', function($scope)
{
$scope.city_data = [
{id:1,
name:'Rajkot'},
{id:2,
name:'Morbi'}
];
});
app.controller('CityIdController', function($scope,$routeParams)
{
console.log($routeParams.city_id);
$scope.city_id = $routeParams.city_id;
});
</script>
</body>
</html>
city.html
<div ng-repeat="x in city_data">
{{x.name}}
</div>
city_id.html
Clicked City Id is : {{city_id}}
You can pass query string parameter with your route like this
$location.path('/YourView/').search({ city: $scope.selectedcity });
then access the routeparameter on YourView like this.
console.log('selected brand ' + $routeParams.brand);
Note
This will work properly provided you have set up your route correctly.

UI Bootstrap Modal popup not working correctly with AngularJS

My code is like this
angular.module('RateRequestApp.controllers', []).controller('ReadOnlyController', [ '$scope', '$modal',
function($scope, $modal) {
var data = [];
data.push("first message");
this.openReprintModal = function() {
var modalInstance = $modal.open({
templateUrl: 'ReprintModal.html',
controller: 'ModalInstanceCtrl',
resolve: {
items: function() {
return data;
}
}
});
};
this.openReprintModal();
}
]);
angular.module('RateRequestApp.controllers').controller('ModalInstanceCtrl', function($scope, $modalInstance) {
$scope.ok = function() {
$modalInstance.close();
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
});
<div id="RateRequestApp" class="content" ng-app='RateRequestApp' ng-controller="ReadOnlyController">
<script type="text/ng-template" id="ReprintModal.html">
<div class="modal-header">
<h3 class="modal-title">Check this out</h3>
</div>
<div class="modal-body">
<ul>
<li ng-repeat="item in items">
<span>{{ item }}</span>
</li>
</ul>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</script>
</div>
All works Okay Except there is no message shown at the body of modal. Apparently everyhting works except `
<li ng-repeat="item in items">
<span>{{ item }}</span>
</li>`
This part is not working.Can any one point out any possible reason.
Note: I am using this one for model :http://angular-ui.github.io/bootstrap/
You have to inject items object to your ModalInstanceCtrl like this:
angular.module('RateRequestApp.controllers')
.controller('ModalInstanceCtrl', function($scope, $modalInstance, items) {
$scope.items = items;
...
});
And then you are able to access it in your view just like you have it now
<li ng-repeat="item in items">
<span>{{ item }}</span>
</li>

Categories