Angular JS get selected item value li html - angularjs

I have angular list and want to get selected value of it but its only working on click event
<div ng-hide="hideCustomerDropdown" id="customer-dropdown" class="slidedown-menu">
<div class="slidedown-header">
</div>
<div class="slidedown-body">
<ul class="customer-list list-unstyled">
<li ng-repeat="customers in customerArray" >
<span class="fa fa-fw fa-user"></span>{{ customers.customer_name }} ({{ customers.customer_mobile || customers.customer_email }})
</li>
</ul>
</div>
</div>
controller:
$("#customer-name").on("click", function() {
$scope.showCustomerList(true);
});
$scope.showCustomerList = function (isClick) {
$http({
url: API_URL ,
method: "GET",
cache: false,
processData: false,
contentType: false,
dataType: "json"
}).
then(function(response) {
$scope.hideCustomerDropdown = false;
$scope.customerArray = [];
window.angular.forEach(response.data, function(customerItem, key) {
if (customerItem) {
$scope.customerArray.push(customerItem);
}
});
}, function(response) {
window.toastr.error(response.data.errorMsg, "Warning!");
});
};

Not sure to understand your question but try to re-render your template by adding
$scope.$apply();
at the end of your then function.

Related

Listing Folders AngularJS

I want to ng-repeat some kind of folders, here is my code : HTML:
<div class="container" ng-controller="miControlador">
<li class="left-menu-list-submenu">
<a class="left-menu-link" href="javascript: void(0);" ng-click="vm.getfolders();">
<i class="left-menu-link-icon fa fa-folder"></i>
Catalogs
</a>
<ul class="left-menu-list list-unstyled" style="margin-left:20px;" ng-repeat="fol in folders">
<li>
<a style="cursor:pointer;" ng-click="vm.more_folders();">{{fol}}</a>
<br />
<a style="cursor:default;color:black;" ng-repeat="more in more_folders">
<ul>
<li>{{more}}</li>
</ul>
</a>
</li>
</ul>
</li>
</div>
Js:
var vm = this;
vm.getfolders = function(){
$http({
method: 'GET' ,
url: 'link_folders.json',
})
.then(function successCallback(data) {
console.log("folders");
$scope.folders = data.data;
}, function errorCallback(response) {
console.log(response);
console.log('error');
});
};
vm.getfolders();
vm.more_folders = function(){
$http({
method: 'GET' ,
url: 'more_folders.json',
})
.then(function successCallback(data) {
console.log("more_folders");
$scope.more_folders = data.data;
}, function errorCallback(response) {
console.log(response);
console.log('error');
});
};
vm.more_folders();
link_folders.json:
[
"/visualizer/360",
"/visualizer/2D"
]
more_folders.json:
[
"/visualizer/360/Eva",
"/visualizer/2D/Ferb",
"/visualizer/360/Andy",
"/visualizer/2D/John"
]
Here is my plunker : https://plnkr.co/edit/SW7fqSajpYtQCJdY6wZb?p=preview
What i want - ng-repeat only this objects, which string is like above catalog, something like that -
/visualizer/2D
/visualizer/2D/Ferb
/visualizer/2D/John
Thanks for answers in advance!
What i want - ng-repeat only this objects, which string is like above
catalog, something like that -
/visualizer/2D
/visualizer/2D/Ferb /visualizer/2D/John
To get data filtered like that, All you need is a filter on your second ng-repeat
ng-repeat="more in more_folders | filter: fol ">
This will filter and then print the result which match your fol data.
To read more about filter, refer to this

Execute a function when the page is loaded angular

I have this function selectHotel() which executes when the select box is clicked and I have used GET method to call data and display it on my view.
I have two options on my select area and it fetches different data for both of them. I want the data of my first option to be displayed when the page is loaded and not when I click the select box.
<div class="row">
<div class ="form_group">
<select ng-click="selectHotel()" class="form-control" ng-options='item as item.hotel_name for item in hotels.data' ng-model='current_Hotel'></select>
Check In:<input type="date">
Check Out:<input type="date">
</div>
<div class="col-md-6">
<h1>{{current_Hotel.hotel_name}}</h1>
<p>{{current_Hotel.hotel_description}}</p>
<img id="hotelImg" class="img img-responsive" ng-src="{{current_Hotel.image_url}}">
<btn class="btn btn-primary">Book a room </btn>
</div>
</div>
<div class="row" ng-repeat="x in roomdata.data">
<div class="well well-sm" >{{x.room_type}}Room Details
</div>
<h5>{{x.rack_price}}<br>Per room per night</h5>
Adult: <select>
<option>1</option>
<option selected="selected">{{x.max_people}}</option>
</select>
Child: <select>
<option>{{x.max_child}}</option>
</select>
</div>
Here is the controller
var app = angular.module('myApp', []);
app.controller('ctrl1', function ($scope, $http) {
$scope.current_Hotel = {
hotel_id: "",
hotel_name: "",
hotel_description: "",
exterior_image: "",
image_url: ""
};
$http({
url: '',
method: "POST",
data: 'postData',
headers: {
'Authorization': ''
}
}).then(function (response) {
$scope.hotels = response.data;
$scope.current_Hotel = $scope.hotels.data[0];
});
$scope.selectHotel = function () {
$http({
method: 'GET',
url: '&image_id=' + $scope.current_Hotel.exterior_image
}).then(function (response) {
var imgdata = response.data;
var imgdata1 = imgdata.data.image_name;
$scope.current_Hotel.image_url = "" + imgdata1;
});
$http({
method:'GET',
url: '&hotel_id=' +$scope.current_Hotel.hotel_id
}).then(function(response){
$scope.roomdata = response.data;
});
};
});
Change your HTMl to invoke a changeHotel when different option is selected.
Invoke changeHotel after all the hotels are loaded passing the first item in the hotel list. This will load the data for the first hotel as per your necessity.
HTML:
<select ng-options="hotel as hotel.name for hotel in hotels"
ng-model="currentHotel"
ng-change="changeHotel(currentHotel)">
</select>
<p>{{disp}}</p>
JavaScript:
$http.get('API_URL')
.then(function(res) {
$scope.hotels = res.data;
$scope.currentHotel = res.data[0];
$scope.changeHotel($scope.currentHotel);
});
$scope.changeHotel = function(hotel) {
$scope.currentHotel = hotel;
$scope.disp = "This is data for current hotel : " + $scope.currentHotel.name;
// stuffs ...
};
Check this CodePen Demo

How to hide an element while using a directive?

I have made a directive in which a single template is using for three functions in a controller. The model for the fields are same. I want to hide a field if the directive is called third time.
<div class="active tab-pane " ng-if="linkid === '1'">
<mallsonline-product info="active_products"></mallsonline-product>
</div>
<!--Active products list ends here -->
<!-- Get Inactive Products -->
<div class="active tab-pane" ng-if="linkid === '2'" >
<mallsonline-product info="inactive_products"></mallsonline-product>
</div>
<!--Get most viewed products ends here -->
<div class="active tab-pane" ng-if="linkid === '3'" >
<mallsonline-product info="mostviewed_products"></mallsonline-product>
</div>
My controller looks something like this
mainControllers.controller('DashboardController', ['$scope', '$http', '$routeParams', '$cookies', '$rootScope', function ($scope, $http, $routeParams, $cookies, $rootScope) {
/* Getting all grid links */
$scope.grLinks = function (Id) {
console.log(Id);
$scope.linkid = Id;
};
/* Getting all grid links ends here */
/* Getting all active product list */
$scope.active_product = function () {
$http.get('js/active-products.json',
{headers:
{'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': $rootScope.keyword_auth_token}
})
.success(function (data) {
$scope.active_products = data.items;
console.log($scope.active_products);
})
.error(function (data) {
console.log(data);
});
};
/* Getting all active product ends here */
/* Getting all inactive product */
$scope.inactive_product = function () {
$http.get('js/inactive-products.json',
{headers:
{'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': $rootScope.keyword_auth_token}
})
.success(function (data) {
$scope.inactive_products = data.items;
console.log($scope.inactive_products);
})
.error(function (data) {
console.log(data);
});
};
/* Getting all inactive product */
/* Getting all most viewed products */
$scope.most_viewed = function () {
$http.get('js/most-viewed.json',
{headers:
{'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': $rootScope.keyword_auth_token}
})
.success(function (data) {
$scope.mostviewed_products = data.items;
console.log($scope.mostviewed_products);
})
.error(function (data) {
console.log(data);
});
};
/* Getting all most viewed products */
$scope.active_product();
$scope.inactive_product();
$scope.most_viewed();
}]);
/* Active products / Inactive and most viewed Directive */
mainControllers.directive('mallsonlineProduct', function () {
return {
restrict: 'E',
scope: {
productInfo: '=info'
},
templateUrl: 'directives/dashboard_product.html'
};
});
/* Active products / Inactive directive ends here*/
and the template looks like this
<li class="bord-1-solid-ccc mg-bt-25" ng-repeat="active_products in productInfo">
<article class="aa-properties-item mg-top-0-notimp">
<a class="aa-properties-item-img" href="#/product">
<img alt="img" class="twohun-oneseventy" src="img/item/6.jpg">
</a>
<div class="aa-properties-item-content">
<div class="aa-properties-about padding-0-notimp">
<h5>{{active_products.name}}</h5>
<p class="font-size-11-imp"><i class="fa fa-building-o" aria-hidden="true"></i> {{active_products.mall.name}}</p>
<p class="font-size-11-imp"><i class="fa fa-map-marker" aria-hidden="true"></i> {{active_products.mall.address}}</p>
<p class="font-size-11-imp"><i class="fa fa-phone" aria-hidden="true"></i> {{active_products.shop.telephone}}</p>
<p class="font-size-11-imp"><i class="fa fa-eye" aria-hidden="true"></i> {{active_products.views}}</p>
</div>
</div>
</article>
</li>
all the fields are present in the model I want to show the active_products.view only when info="mostviewed_products". How can I achieve this ?
Had passed "linkid" in directive to know the current linkid value in template
Please make following changes
Directive
mainControllers.directive('mallsonlineProduct', function () {
return {
restrict: 'E',
scope: {
productInfo: '=info',
linkid:'=linkid'
},
templateUrl: 'directives/dashboard_product.html'
};
});
Html
<div class="active tab-pane " ng-if="linkid === '1'">
<mallsonline-product info="active_products" linkid="linkid"></mallsonline-product>
</div>
<!--Active products list ends here -->
<!-- Get Inactive Products -->
<div class="active tab-pane" ng-if="linkid === '2'" >
<mallsonline-product info="inactive_products" linkid="linkid"></mallsonline-product>
</div>
<!--Get most viewed products ends here -->
<div class="active tab-pane" ng-if="linkid === '3'" >
<mallsonline-product info="mostviewed_products" linkid="linkid"></mallsonline-product>
</div>
In template ('directives/dashboard_product.html')
<p class="font-size-11-imp"><i class="fa fa-eye" aria-hidden="true" ng-if="linkid==3"></i> {{active_products.views}}</p>
Hope this will resolve your issue.

How do I open a modal from a controller using Angular-materialize

I am using Materialize CSS and the Angular-materialize directives:
http://materializecss.com/modals.html
http://krescruz.github.io/angular-materialize/#modals
I am trying to do the following
User clicks button
Controller action gets fired and we go get data from an api
Modal is displayed to user and data returned is displayed
I have the following button
<a href="#MyModal" modal class="my-modal-trigger waves-effect waves-green btn right"Show Data/a>
and modal
<div id="MyModal" class="modal">
<div class="modal-content center">
<div class="row">
<div class="row left">
<div class="card blue-grey darken-1">
<div class="card-content white-text">
<span class="card-title">Data</span>
</div>
<div>
<ul class="collection">
//loop the data
</ul>
</div>
</div>
<a class="modal-action modal-close waves-effect waves-green btn">Close</a>
</div>
</div>
</div>
</div>
and i have the following in my JS
var app = angular.module("MyApp", ['ngRoute', 'ui.materialize']);
How can i call a controller method to pop up the modal and fill it with data, from my controller
app.controller('mainController', function ($scope, $location, $http, AppConfig) {
var params = { some stuff}
$http({
method: 'POST',
url: myURL,
headers: {
'Content-Type': 'text/html',
'Accept': 'application/json'
},
params: params
})
.success(function (data) {
//pop up the modal and show the data
Materialize.toast('Awesome, we got the data', 4000);
})
.error(function (status) {
Materialize.toast('Bad stuff happened', 4000);
});
});
Angular-materialize lets you set an option open in your trigger. Use it to specify a variable that, when true, will launch your modal. Set it to false initially in your controller.
Use ng-click to call a function in your controller that fetches data from your API then sets the open variable to true on success.
Trigger:
<a href="#MyModal" class="btn" modal open="openModal"
ng-click="getDataOpenModal()">Show Data</a>
In Controller:
$scope.openModal = false;
$scope.getDataOpenModal = function() {
$http({
method: 'POST',
url: '/myUrl',
headers: {
'Content-Type': 'text/html',
'Accept': 'application/json'
},
params: params
})
.success(function(data) {
$scope.data = data;
$scope.openModal = true;
Materialize.toast('Awesome, we got the data', 4000);
})
.error(function(status) {
Materialize.toast('Bad stuff happened', 4000);
});
}
EDIT: There are two other options you can set in your trigger, ready and complete
HTML
<a href="#MyModal" class="btn" modal open="openModal"
ready="readyCallback()" complete="completeCallback()"
ng-click="getDataOpenModal()">Show Data</a>
JS
$scope.readyCallback = function() {
Materialize.toast("Modal ready", 4000);
}
$scope.completeCallback = function() {
Materialize.toast("Modal complete", 4000);
}
Worked for me with $scope.$apply() after $scope.openModal = true;
I was fighting with this too, but no solution worked for me. I had to change html side.
My html:
<i class="zmdi zmdi-eye"></i>
In controller:
$scope.openModal = false
$scope.get_info_log = function(){
$scope.openModal = true;
}
Data-target should match your modal id:
!-- Modal Structure-->
<div id="log_detail" class="modal modal-fixed-footer setup-modal">
<div class="modal-content">
</div>
</div>
<div class="modal-footer">
<a class=" modal-action modal-close waves-effect waves-light btn">Close</a>
</div>
</div>

AngularJS $resource custom urls not working

I have these 2 services:
.factory('HttpHandler', function() {
return {
loadData: function (promise) {
var self = {
data: [],
loading: true,
promise: promise
};
promise.then(function (data) {
self.data = data;
self.loading = false;
});
promise.finally(function () {
self.loading = false;
});
return self;
}
};
})
.factory('Order', ['$resource', '$filter', 'apiUrl', function ($resource, $filter, api) {
var Order = $resource(api + 'orders/:path', {
path: '#path'
}, {
recent: {
method: 'GET',
params: {
path: 'recent'
},
isArray: true
}
}, {
failures: {
method: 'GET',
params: {
path: 'failures'
},
isArray: true
}
}, {
exceptions: {
method: 'GET',
params: {
path: 'exceptions'
},
isArray: true
}
});
angular.extend(Order.prototype, {
getDescription: function () {
var rolls = 0,
cuts = 0,
skus = [],
lines = $filter('orderBy')(this.lines, 'sku');
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
switch (line.type) {
case 0: // cut
cuts++;
break;
case 1: // roll
rolls++
break;
}
if (skus.indexOf(line.sku) == -1) {
skus.push(line.sku);
}
}
var description = '';
description += cuts > 0 ? cuts > 1 ? cuts + ' x cuts' : cuts + ' x cut' : '';
description += rolls > 0 && description.length > 0 ? ', ' : '';
description += rolls > 0 ? rolls > 1 ? rolls + ' x rolls' : rolls + ' x roll' : '';
description += skus.length == 1 ? ' of ' + skus[0] : '';
return description;
}
});
return Order;
}]);
As you can see, I have defined 3 different paths to use:
orders/recent
orders/failures
orders/exceptions
I have this controller:
.controller('CustomerServicesController', ['HttpHandler', 'Order', function (handler, Order) {
var self = this;
self.recent = handler.loadData(Order.recent({ limit: 30 }).$promise);
self.failures = handler.loadData(Order.failures({ limit: 30 }).$promise);
self.exceptions = handler.loadData(Order.exceptions({ limit: 30 }).$promise);
}])
When I run my application, I get an error stating:
undefined is not a function
on the line that states self.failures = handler.loadData(Order.failures({ limit: 30 }).$promise);.
If I comment out the 2 lines so the controller becomes:
.controller('CustomerServicesController', ['HttpHandler', 'Order', function (handler, Order) {
var self = this;
self.recent = handler.loadData(Order.recent({ limit: 30 }).$promise);
//self.failures = handler.loadData(Order.failures({ limit: 30 }).$promise);
//self.exceptions = handler.loadData(Order.exceptions({ limit: 30 }).$promise);
}])
Everything works fine....
I think it has something to do with the $resource but I can't figure it out.
Just for completeness sake, here is the template file:
<div class="row">
<a class="back" href="/"><i class="fa fa-arrow-circle-left"></i></a>
<section class="large-4 columns">
<h1 class="column-title">Orders <small>quick search</small></h1>
<form name="orderFrom" role="form" ng-submit="customerServices.orderSearch()">
<div class="row collapse">
<div class="small-10 columns typeahead-icon">
<input type="text" ng-model="customerServices.searchTerm" placeholder="Search" typeahead="item for items in customerServices.autoComplete() | filter:$viewValue" typeahead-loading="customerServices.loading" typeahead-min-length="2">
<i ng-show="customerServices.loading" class="fa fa-spinner fa-spin"></i>
</div>
<div class="small-2 columns">
<button type="submit" class="button postfix">Go</button>
</div>
</div>
</form>
</section>
<section class="tile-column large-8 columns" tile-column>
<h1 class="column-title">Recent orders</h1>
<div class="loading" ajax-loader ng-show="customerServices.recent.loading"></div>
<div class="alert alert-box" ng-show="!customerServices.recent.loading && customerServices.recent.data.length === 0">
No records have been found that match your search.
×
</div>
<a class="tile large" ng-href="/customer-services/view-order/{{order.orderNumber}}" tile ng-repeat="order in customerServices.recent.data" id="{{order.orderNumber}}">
<div class="text">
<strong ng-bind="order.account.accountNumber"></strong> <span ng-bind="order.account.name"></span><br />
<span ng-bind="order.raisedBy"></span><br />
<span ng-bind="order.orderNumber"></span><br />
<span ng-bind="order.getDescription()"></span><br />
</div>
</a>
</section>
<section class="tile-column large-8 columns" tile-column>
<h1 class="column-title">Sync failures</h1>
<div class="loading" ajax-loader ng-show="customerServices.failures.loading"></div>
<div class="alert alert-box" ng-show="!customerServices.failures.loading && customerServices.failures.data.length === 0">
No records have been found that match your search.
×
</div>
<a class="tile large" ng-href="/customer-services/view-order/{{order.orderNumber}}" tile ng-repeat="order in customerServices.failures.data" id="{{order.orderNumber}}">
<div class="text">
<strong ng-bind="order.account.accountNumber"></strong> <span ng-bind="order.account.name"></span><br />
<span ng-bind="order.raisedBy"></span><br />
<span ng-bind="order.orderNumber"></span><br />
<span ng-bind="order.getDescription()"></span><br />
</div>
</a>
</section>
<section class="tile-column large-8 columns" tile-column>
<h1 class="column-title">Exceptions</h1>
<div class="loading" ajax-loader ng-show="customerServices.exceptions.loading"></div>
<div class="alert alert-box" ng-show="!customerServices.exceptions.loading && customerServices.exceptions.data.length === 0">
No records have been found that match your search.
×
</div>
<a class="tile large" ng-href="/customer-services/view-order/{{order.orderNumber}}" tile ng-repeat="order in customerServices.exceptions.data" id="{{order.orderNumber}}">
<div class="text">
<strong ng-bind="order.account.accountNumber"></strong> <span ng-bind="order.account.name"></span><br />
<span ng-bind="order.raisedBy"></span><br />
<span ng-bind="order.orderNumber"></span><br />
<span ng-bind="order.getDescription()"></span><br />
</div>
</a>
</section>
</div>
Can anyone tell me why this isn't working?
Figured it out, it was a syntax error on my part in the Order service. It should be:
var Order = $resource(api + 'orders/:path', {
path: '#path'
}, {
recent: {
method: 'GET',
params: {
path: 'recent'
},
isArray: true
},
failures: {
method: 'GET',
params: {
path: 'failures'
},
isArray: true
},
exceptions: {
method: 'GET',
params: {
path: 'exceptions'
},
isArray: true
}
});
and NOT
var Order = $resource(api + 'orders/:path', {
path: '#path'
}, {
recent: {
method: 'GET',
params: {
path: 'recent'
},
isArray: true
}
}, {
failures: {
method: 'GET',
params: {
path: 'failures'
},
isArray: true
}
}, {
exceptions: {
method: 'GET',
params: {
path: 'exceptions'
},
isArray: true
}
});
subtle difference :)

Resources