How to increase a number in badge on ionic - javascript

I'd like to increase a number in a badge.
I set the number 0 in 'app.js'.
And I made minus button, plus button and textbox.
There is a number in the textbox.
If I tab the minus or plus button, the number would change.
I added an action in the button click function.
But the number in badge is not changed.
This is my code to change the number.
example.controller('EventController', ['$scope', function($scope) {
$scope.count = 0;
$scope.countBadge = 0;
$scope.$on('orderMinus', function() {
if($scope.count!=0){
$scope.count--;
}
if($scope.countBadge != 0){
$scope.countBadge--;
}
});
$scope.$on('orderPlus', function() {
if($scope.count<=29){
$scope.count++;
$scope.countBadge++;
}
});
}]);
<script id="page_dish.html" type="text/ng-template">
<div>
<ion-header-bar style="height:10%; background: none; border-bottom: none">
<a id = "button_menuList" href="#/page_menuList"></a>
<a id = "img_chopchop"></a>
<div ng-controller="EventController">
<span class="badge badge-assertive">{{countBadge}}</span>
</div>
<a id = "button_basket" href="#/page_join"></a>
</ion-header-bar>
</div>
<ion-view class = "page_dish" ng-controller="AppCtrl">
<ion-content class = "no-header no-footer" has-bouncing="false">
<ion-slide-box>
<ion-slide class = "episode1">
<div align = "left">
<img src="img/Episode/Main/Episode1/Text_title.png" style="width:80%; margin-left:5%; margin-top:25%;">
<img src="img/Episode/Main/Episode1/Label_price.png" style="width:40%; margin-left:5%; margin-top:4%;">
</div>
<div>
<a id = "button_learnMore1" ng-click="modal.show()"></a>
</div>
<div align = "left" ng-controller="EventController">
<a class = "button_minus1" ng-click="$emit('orderMinus')"></a>
<input type="text" style="position:absolute; width:95px; height:65px; margin-left:37.4%; font-size:55px; color:#ffffff; background-color:transparent; text-align:center;" value = {{count}} readonly = "true">
<a class = "button_plus1" ng-click="$emit('orderPlus')"></a>
</div>
</ion-slide>
</ion-slide-box>
</ion-content>
</ion-view>
</script>
How to fix my code to change the number in badge with click the button.
Please, help me.

The problem with your code is that you are instantiating several times EventController, so the $scope is different for each instance (that's the reason why in the $scope where the buttons exist the counter gets updated, but on the other EventController $scope it won't: it's not listening the same scope events).
Considering your approach, the easiest solution is to use $rootScope instead of $scope, so you listen and emit on $rootScope and both EventControllers notice the changes.
Another cleaner approach which I'd prefer is to put count and countBadge inside a service (that is a singleton), and create a watch to ensure that when counter is updated by one controller, the other one gets the updated value.
I attach the first solution in code snippet, cleaning a little bit the code to make it clear:
example.controller('EventController', ['$scope', '$rootScope', function($scope, $rootScope) {
$scope.count = 0;
$scope.countBadge = 0;
$scope.emit = $rootScope.$emit;
$rootScope.$on('orderMinus', function() {
if($scope.count!=0){
$scope.count--;
}
if($scope.countBadge != 0){
$scope.countBadge--;
}
});
$rootScope.$on('orderPlus', function() {
if($scope.count<=29){
$scope.count++;
$scope.countBadge++;
}
});
}]);
<script id="page_dish.html" type="text/ng-template">
<div>
<ion-header-bar style="height:10%; background: none; border-bottom: none">
<a id = "button_menuList" href="#/page_menuList"></a>
<a id = "img_chopchop"></a>
<div ng-controller="EventController">
<span class="badge badge-assertive">{{countBadge}}</span>
</div>
<a id = "button_basket" href="#/page_join"></a>
</ion-header-bar>
</div>
<ion-view class = "page_dish" ng-controller="AppCtrl">
<ion-content class = "no-header no-footer" has-bouncing="false">
<!-- some stuff -->
<div align = "left" ng-controller="EventController">
<a class = "button_minus1" ng-click="emit('orderMinus')"></a>
<!-- some more stuff -->
<a class = "button_plus1" ng-click="emit('orderPlus')"></a>
<!-- some more stuff -->
</ion-content>
</ion-view>
</script>

Related

Angularjs Ui-Bootstrap modal popup inside specified element

i have a problem with my code , this code is about append a modal to element with specific id. so that when button clicked ,this modal popup will showed inside div element with id="forModal" (div element with this id is inside view.html) ,my app using angularjs that have base html(index.html) ,one template for route(view.html),one template for modal(modal.html).
index.html
<html>
<head>
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!--Ui Route-->
<script src="lib/ionic/js/angular-ui/angular-ui-router.min.js"> </script>
<!--UI Bootstrap-->
<script src="lib/ionic/js/angular-ui/ui-bootstrap-2.5.0.min.js"></script>
<!--UI Bootstrap TPLS-->
<script src="lib/ionic/js/angular-ui/ui-bootstrap-2.5.0-tpls.min.js"></script>
<!--ngCoockies-->
<script src="js/angular-cookies.js"></script>
<!-- my app's js -->
<script src="js/app.js"></script>
<!--controller js-->
<script src="js/controller.js"></script>
</head>
<body ng-app="starter">
<ui-view></ui-view>
</body>
</html>
app.js
var moduleapp = angular.module('starter', ['ionic','ui.router','ngCookies','ui.bootstrap']);
moduleapp.config(function($stateProvider,$urlRouterProvider){
$stateProvider.state("dashboard",{
url:"/dashboard",
templateUrl:"templates/dashboard.html",
controller : "dashboardCtrl"
})
$stateProvider.state("dashboard.view",{
url : "/view",
templateUrl : "templates/view.html",
controller: "viewDataCtrl"
})
$urlRouterProvider.otherwise("/dashboard.view")
})
controller.js
moduleapp.controller('dashboardCtrl',[function(){
//some code
}])
moduleapp.controller('viewDataCtrl',['$document','$uibModal','$scope','$http','$cookies',function($document,$uibModal,$scope,$http,$cookies){
// reserve variable,declare it as object
$scope.dataColumn = {};
$scope.dataData = {};
// reserve variable for user authetication level
$scope.userLevel= $cookies.get('userLevel');
//function for finding available column
function caricolumn(){
$http.get('link for search column.php').success(function(hasil){
$scope.dataColumn = hasil;
});
}
//executing function when controller running
caricolumn();
//function for get data,return result to $scope.dataData as object
function caridata(){
$http.get('link for search data.php').success(function(hasil){
$scope.dataData = hasil;
})
}
//execute function when controller running
caridata();
//function for edit
$scope.edit = function(x){
var modalInstance = $uibModal.open({
templateUrl:'templates/modal.html',
controller:'viewDataCtrl',
//THIS IS THE PROBLEM ,appendTO doesnt work,still inject modal popup to body element
appendTo : angular.element(document.querySelector('#viewElement'))
});
}
//function for delete data
$scope.delete = function(x){
$http.post('link for deletedata.php',x).success(function(hasil){
alert(hasil);
//if output(php echo) same as string ,this condition considered as success
if(hasil == "Delete Success"){
caridata();
}
})
}
}]);
modal.html
<div class="modal-header">
<h3>Hayy</h3>
</div>
<div class="modal-body">
<p>this is Body</p>
</div>
<div class="modal-footer">
this is footer
</div>
dashboard.html
<ion-side-menus enable-menu-with-back-views="false">
<ion-side-menu-content>
<ion-nav-bar class="bar-stable">
<ion-nav-back-button>
</ion-nav-back-button>
<ion-nav-buttons side="left">
<button class="button button-icon button-clear ion-navicon" menu-toggle="left">
</button>
</ion-nav-buttons>
</ion-nav-bar>
<ui-view>
<!--This is where view.html injected-->
</ui-view>
</ion-side-menu-content>
<ion-side-menu side="left">
<ion-header-bar class="bar-stable">
<h1 class="title">Menu</h1>
</ion-header-bar>
<ion-content>
<ion-list ><a ui-sref="dashboard.add">
<ion-item>Tambah Data</ion-item></a>
</ion-list>
<ion-list ><a ui-sref="dashboard.view">
<ion-item>Tampil Data</ion-item></a>
</ion-list>
<ion-list >
<a ng-click="logout()">
<ion-item>Log Out</ion-item>
</a>
</ion-list>
</ion-content>
</ion-side-menu>
</ion-side-menus>
view.html
<div id="viewElement" class="container" style="margin-top:50px;">
<h2>Data-Data</h2>
<hr/>
<table class="table table-bordered">
<thead>
<tr>
<th ng-repeat="dc in dataColumn">{{dc.KOLOM}}</th>
<th ng-if="userLevel == 'LV02' || userLevel == 'LV01'">Edit</th>
<th ng-if="userLevel == 'LV01'">Delete</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="dd in dataData" id="dt{{dd.IDROW}}">
<td ng-repeat="ddd in dd.DATA">{{ddd}}</td>
<td ng-if="userLevel == 'LV01' || userLevel == 'LV01'"><button type="button" ng-click="edit({{dd.IDROW}})" class="btn btn-warning">Edit</button></td>
<td ng-if="userLevel == 'LV01'"><button type="button" ng-click="delete({{dd.IDROW}})" class="btn btn-danger">Delete</button></td>
</tr>
</tbody>
</table>
</div>
as you can see ,when app running .route default will go to "dashboard.view"
dashboard state is code for left sidemenu ,then dashboard.view state for viewing data(view state in child from dashboard state)
what i want is when edit button clicked inside view.html(controller : viewDataCtrl,state : dashboard.view), modal popup will appear inside div element with id="forModal" (div element with this id is inside view.html)
but with this code ,modal popup always appear inside body tag element not inside div element with id="forModal".
how can i approach this condition ? thanks

how to select by classname in angular from json

I am trying to get an inner value of an element by selecting through the class in angular. But for some reason it keeps giving me an error when I try to select var highlighted = angular.element(element.getElementsByClassName("btn-danger")); This is the error
angular.js:13642TypeError: angular.element.getElementsByClassName is not a function
Could it be because I am mixing angular and jquery together
the main problem is in the click controller.
it gets the value of the ul that gets loaded with the json and supposed to show on the bottom in the mouse click me(the number is just for testing)
the project is a single click keyboard that will eventually have an interval and switch keys so a disabled person can type with only one click
here is the view
<body ng-controller="mainController" ng-click="textArea = textArea + 1">
<div ng-controller="clickController">
<header>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">Click and Type</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li><i class="fa fa-home"></i> Home</li>
</ul>
</div>
</nav>
</header>
<div class="container">
<div ng-controller="intervalController">
<ul class="general_button" ng-repeat="letter in language[0].rows track by $index" ng-init="rowIndex = $index"> {{rowIndex}}
<button type="button" class="btn " ng-class="{true:'btn-danger', false:'btn-info'}[rowIndex ==isSelected() || columnIndex == isSelected()]" ng-repeat="single in letter track by $index" ng-init="columnIndex = $index">
{{columnIndex}}{{single}}
</button>
</ul>
<div >
<h1 ng-mousemove="textArea = textArea + 1">Mouse over me!</h1>
<label for="inputlg">input-lg</label>
<input class="form-control input-lg" id="inputlg" type="text" value="{{ textArea + highlightedLetter }}">
</div>
</div>
</div>
</div>
</body>
</html>
and here is the model
var App = angular.module('App', []);
var theLanguage = 'english';
App.factory('jsonLanguage', function($http){
var theLanguage = 'english';
return {
get: function(theLanguage){
//var url = theLanguage + '.json';
var url = 'english.json';
return $http.get(url);
}
}
});
App.controller('mainController', function($scope, $http, $log, jsonLanguage) {
jsonLanguage.get().then(function(res){
$scope.language = res.data;
$log.log($scope.language);
});
$scope.isSelected = function(rowIndex, columnIndex) {
return 0;
}
});
App.controller('intervalController', function($scope, $log) {
this.$log = $log;
//var name = $scope.single;
//$log.log(name);
});
App.controller('clickController', function($scope, $log) {
$scope.$log = $log;
var highlighted = angular.element(angular.element.getElementsByClassName("btn-danger"));
alert($scope.highlightedLetter = highlighted.value);
});
I greatly appreciate any help as I am new to angular.
There's no getElementsByClassName method in Jquery. Try using standard DOM query:
var highlighted = angular.element(document.querySelector(".btn-danger"));
getElementsByClassName is a function of DOM element, not jQuery.
Try this, it might help you:
var classElement = document.getElementsByClassName("multi-files");
var highlighted= angular.element(classElement);

nested ng-repeat index not working || nested ng-click not working

if we create two or three comment with multiple replies to them the "helpful" link is causing problem when clicked it perform ng-click operation on the index with same number thus showing all the text with same index. how to resolve this nesting so that when a link is clicked only the respective text is shown
http://plnkr.co/edit/XS4Nro3sdIWMnopdgDYG?p=preview
the ng-click and ng-show operation are working through myDiscuss controller
var app = angular.module("myDiscuss", []);
app.controller("TabController", function($scope) {
$scope.subTab = null;
$scope.subLike=null;
$scope.selectSubLike = function (setTab) {
$scope.subLike=setTab;
}
$scope.selectSubTab = function(setTab){
$scope.subTab = setTab;
};
$scope.isSelectedSub = function(checkTab){
return $scope.subTab === checkTab;
};
$scope.isSelectedSubLike = function(checkTab){
return $scope.subLike===checkTab;
};
});
For html file look in the plunker link.
Helpful and Reply link are in the reply-link.html file
Here is a Plunker: http://plnkr.co/edit/PQ36lMXR1YOs8DP7WXMk?p=preview
What I did is added helpful: 0 to both comment and reply objects. Also added <p ng-if="object.helpful">{{ object.helpful }} </p> to comment-section.html and reply-box.html
Then when clicking on the helpful added a new function called increaseHelpful(object) where you increase the helpful variable by one on each click. Of course you need to make it that one user can only click it once but just for example :)
Get the index1 also in so you can get the reply box where you click the reply button. Use selectSubTab(index, index1) and then have two variables in $scope.subTab to check what is selected.
Edited from Konkko's plnkr http://plnkr.co/edit/lbn57aPTJQpgzMaQPW6t?p=preview
reply-box.html
<div id ="wrapper">
<form ng-submit="replysubmit()" ng-controller="BlockController">
<div class="clearfix" ng-if="isSelectedSub(index)">
<input type="textarea" tabindex="0"
style="overflow: auto; max-height: 350px; margin-top:1px;" class ="col-sm-8 col-md-8 col-lg-11" ng-model="reply.comment"
name="reply.comment" placeholder="Write a Reply" />
</div>
<blockquote ng-repeat="(index1,object) in replybox">
<h4>Name</h4>
<p>
{{object.comment}} {{index1+1}}
</p>
<p ng-if="object.helpful">{{ object.helpful }} </p>
<ul reply-links></ul>
<div class="clearfix" ng-if="isSelectedSub(index, index1)">
<input type="textarea" tabindex="0"
style="overflow: auto; max-height: 350px; margin-top:1px;" class ="col-sm-8 col-md-8 col-lg-11" ng-model="reply.comment"
name="reply.comment" placeholder="test" />
</div>
</blockquote>
</form>
</div>
reply-links.html:
<ul class="nav nav-pills">
<li>
<a href ng-click="increaseHelpful(object)" class="glyphicon ">Helpful</a>
</li>
<li>
<a href ng-click="selectSubTab(index, index1)" class="glyphicon" >Reply</a>
</li>
</ul>
JS:
$scope.subTab = {first: null, second: null};
$scope.selectSubTab = function(setTab, setTab1){
console.log(setTab);console.log(setTab1);
$scope.subTab = {first: setTab, second: setTab1};
};
$scope.isSelectedSub = function(checkTab, checkTab1){
return $scope.subTab.first === checkTab && $scope.subTab.second === checkTab1;
};

orderBy is not updating when I click on a button

Hope somebody can help me with my problem.
I am trying to order my list on specific data and this works fine when I say upfront on what it needs to be sorted.
But when I do this when I click on a button it doesn't order my list in anyway.
Hope somebody can help me with this problem.
this is my app.js code:
app.controller("ListController", function ($scope, $interval, $http, myService, OpenDataService) {
myService.async().then(function (d) {
OpenDataService.opendata = d;
$scope.openData = OpenDataService.opendata;
$scope.order = "";
});
$scope.orderOptions = ["gemeente", "locatie"];
$scope.change = function (value) {
console.log("change");
$scope.order = value;
console.log(value);
}
$scope.test = OpenWifiData;
});
And here is the html code I use:
<li ng-click="change('gemeente')"><a>locatie</a></li>
<div id="WifiSpots" ng-controller="ListController" class="col-sm-12 col-md-4 col-md-offset-2">
<div ng-repeat="item in openData | filter:searchText | orderBy: order">
<ul class="list-group">
<li class="list-group-item">
<div class="row wifiSpots" >
<div class="col-md-2">{{item.locatie}}</div>
<div class="col-md-2">{{item.gemeente}}</div>
<div clas="col-md-1">{{item.distance}}</div>
<div clas="col-md-1">{{item.duration}}</div>
<button ng-controller="MapController" ng-click="calculateAndDisplayRoute(item.objectid)" class="btn ">Selecteer</button>
</div>
</li>
</ul>
</div>
</div>
The 'order' in the ng-repeat directive is in a different scope than the one in your controller. Add a wrapper class like so:
$scope.opts = {order: ""};
Then in your change function update that instead:
$scope.opts.order = value;
In the html:
orderBy:opts.order

AngularJS not filtering products list

I am having an issue with AngularJS filtering my products list. I have done a few console.log queries on my variables and all seem fine. The problem is that the view does not update to show the filtered products.
Filtering works perfectly fine when you enter the search text in the input box but it does not work when clicking on the Category menu items.
I would like to filter the product list by category when the user clicks on the menu item.
Please see my code below and any help or advice is greatly appreciated.
My app.js
myApp.controller('StoreController', function($scope, $filter, storeFactory, cartFactory) {
$scope.cartTotal = 0;
$scope.cartItems = [];
$scope.categories = [];
$scope.counted = 0;
$scope.filteredProducts = {};
//get the products
storeFactory.getProducts(function(results) {
$scope.products = results.products;
$scope.counted = $scope.products.length;
$scope.filteredProducts = results.products;
});
$scope.$watch("search", function(query){
if($scope.filteredProducts.length) {
$scope.filteredProducts = $filter("filter")($scope.products, query);
$scope.counted = $scope.filteredProducts.length;
}
});
$scope.filterProductsByCategory = function(categoryName){
console.log('category filter');
/*$scope.products.forEach(function(o,i){
console.log('filter');
if( o.category_id !== categoryId ){
$scope.filteredProducts.splice(i,1);
console.log('removing');
console.log(o);
}
});*/
$scope.filteredProducts = $filter("filter")($scope.filteredProducts, categoryName);
console.info('the filtered items');
console.log($scope.filteredProducts);
$scope.counted = $scope.filteredProducts.length;
}
$scope.getCategories = function(){
storeFactory.getCategories(function(results){
$scope.categories = results.rows;
});
}
$scope.getCategories();
});
My store.htm
UPDATE :
I removed the extra controller reference and wrapped everything in one div.
<div ng-controller="StoreController">
<!-- the sidebar product menu -->
<div class="block-content collapse in">
<div class="daily" ng-repeat="category in categories | orderBy:'name'">
<div class="accordion-group">
<div ng-click="filterProductsByCategory(category.category_name)" class="accordion-toggle collapsed">{{category.category_name}}</div>
</div>
</div>
</div>
</div>
<!-- Load store items start -->
<div class="label">Showing {{counted}} Product(s)</div>
<div class="row" ng-repeat="product in filteredProducts | orderBy:'product_name'" style="margin-left: 0px; width: 550px;">
<hr></hr>
<div class="span1" style="width: 120px;">
<!-- <a data-toggle="lightbox" href="#carouselLightBox"> -->
<a data-toggle="lightbox" href="#carouselLightBox{{product.product_id}}">
<!--img alt={{ product.product_name }} ng-src="{{product.image}}" src="{{product.image}}" /-->
<img id="tmp" class="" src="images/products/{{product.product_image_filename}}" alt=""></img>
</a>
<div class="lightbox hide fade" id="carouselLightBox{{product.product_id}}" style="display: none;">
<div class='lightbox-content'>
<img src="images/products/{{product.product_image_filename}}" alt="" />
<!--img alt={{ product.product_name }} ng-src="{{product.image}}" src="{{product.image}}" /-->
<button class="btn btn-primary" id="close_lightbox" ng-click="closeBox(product.product_id, $event)">Close</button>
</div>
<style>
#close_lightbox
{
position: absolute;
top: 5px;
right: 5px;
}
</style>
</div>
</div>
<div class="span6" style="width: 330px; margin-bottom: 15px;">
<h5 style="font-size: 14px; font-weight: bold;">{{product.product_name}}</h5>
<p>{{product.product_description }}</p>
<p>Category : {{product.category_name}}</p>
</div>
<div class="span3">
<p class="price">Price : <strong>R{{ product.product_price }}</strong></p>
</div>
</div>
<!-- end of controller -->
</div>
$scope.filteredProducts = {};
//get the products
storeFactory.getProducts(function (results) {
$scope.products = results.products;
$scope.counted = $scope.products.length;
$scope.filteredProducts = results.products;
});
Is results.products an array of objects or an object of objects? Because $filter('filter')($scope.products,query); expects $scope.products to be an array.
$scope.$watch("search", function (query) {
if($scope.filteredProducts.length) {
$scope.filteredProducts = $filter("filter")($scope.products, query);
$scope.counted = $scope.filteredProducts.length;
}
});
Here's what I'm thinking this should look like and you won't need the $watch statement or the filteredProducts array/object, In controller:
$scope.search = '';
$scope.products = [];
$scope.categories = ['category1','category2','category3'];
// assuming that your store function getProducts returns a promise here
storeFactory.getProducts().then(function(results){
$scope.products = results.products; // needs to be an array of product objects
});
$scope.filterProductsByCategory = function(category){
$scope.search = category;
};
Then in your HTML Partial, this is not exactly how your's is, I'm just showing you here in shorter form what is possible:
<button ng-repeat="cat in categories" ng-click="filterProductsByCategory(cat)">{{cat}}</button>
<div class="row" ng-repeat="product in products | filter:search | orderBy:'product_name'">
<!-- Product Information Here -->
</div>
I created a JSFiddle to demonstrate: http://jsfiddle.net/mikeeconroy/QL28C/1/
You can free form search with any term or click a button for a category.
The side bar is using one instance of StoreController, and the main div is using another instance of StoreController. Each instance having its own scope. The should both use the same controller instance: wrap everything inside a div, and use a unique StoreController for this wrapping div.

Categories