AngularJs ng-class active not working - angularjs

HTML Code: active class not working here in the li tag
<ul class="list-group">
<li class="list-group-item" ng-class="{'active': isSelectedBookmark(bookmark.id)}" ng-repeat="bookmark in bookmarks | filter:{category:currentCategory.name}">
<button ng-click="setEditedBookmark(bookmark); startEditing();" type="button" class="btn btn-link">
<span class="glyphicon glyphicon-pencil"></span>
</button>
{{bookmark.title}}
</li>
</ul>
javascript file:
$scope.bookmarks = [
{'id':0, 'title':"AngularJs", 'url':"http://angularjs.org", 'category':"Development"},
{'id':1, 'title':"Egghead.io", 'url':"http://angularjs.org", 'category':"Development"},
{'id':2, 'title':"HTML", 'url':"http://w3schools.com", 'category':"Design"},
{'id':3, 'title':"CSS", 'url':"http://w3schools.com", 'category':"Design"},
{'id':4, 'title':"JavaScript", 'url':"http://w3schools.com", 'category':"Development"}
];
$scope.editedBookmark = null;
function setEditedBookmark(bookmark) {
$scope.editedBookmark = angular.copy(bookmark);
}
function isSelectedBookmark(bookmarkId) {
return $scope.editedBookmark !== null && $scope.editedBookmark.id === bookmarkId;
}
$scope.setEditedBookmark = setEditedBookmark;
$scope.isSelectedBookmark=isSelectedBookmark;
How to make the active class working in this case?

Related

ng-show is not working with ng-repeat

Below is my table markup
<tr ng-show="paginate({{$index+1}})" ng-repeat="x in ProductInfo_Pager | orderBy :sortType:sortReverse | filter:searchText | limitTo : rowPerPage" ng-class="$even?'table-danger':'table-info'">
<td>{{$index+1}}</td>
<td>{{x.Product}}</td>
<td>{{x.Location}}</td>
<td>{{x.Qty}}</td>
<td>{{x.UnitPrice | currency : '₹':2}}</td>
<td class="text-center">
<i class="fa fa-flag" aria-hidden="true" style="color:red" /> |
<i class="fa fa-bolt" aria-hidden="true" style="color:red" /> |
<i class="fa fa-users" aria-hidden="true"></i>
</td>
</tr>
and pager below it
<ul class="pagination">
<li class="page-item" ng-repeat="x in getNumber(rowPerPage) track by $index">
<a class="page-link" ng-click="pagerIndex=$index+1">{{$index+1}}</a>
</li>
</ul>
And AngularJs Code
$scope.ProductInfo_Pager = $scope.ProductInfo;
$scope.sortType = 'Product'; // set the default sort type
$scope.sortReverse = false; // set the default sort order
$scope.searchText = ''; // set the default search/filter term ,
$scope.totalItems = $scope.ProductInfo.length;
$scope.currentPage = 1;
$scope.rowPerPage = 5;
$scope.pagerIndex = 1;
$scope.getNumber = function (num) {
var pages = $window.Math.ceil($scope.totalItems / num);
return new Array(pages);
}
$scope.paginate = function (rowindex) {
var begin, end, index, flag ;
index = $scope.pagerIndex;
end = (index * $scope.rowPerPage) - 1; // -1 to sync it with zero based index
begin = end - $scope.rowPerPage + 1;
if(rowindex >=begin && rowindex <= end ){
flag=true;
}
else{
flag=false;
}
var d = 0;
return flag;
};
paginate function() return true or false based on logic which is used in ng-show in tr tag with ng-repeat, but its not doing show , hide functionality as expected
Logic is :
Suppose rowPerPage is 5 - [5 row can be show up in table at a time]
And we click on 4 in pager so it should show row from 16-20 .
In ng-show paginate function is bind which take row index as parameter , this function check if rowindex falls in between 16 - 20 , if yes than it return true (ng-show=true) else false and accordingly should hide that row.
As per mu understanding its two way binding so any change in ng-show should work perfectly but it does not show any effect
Can someone help me why this is happening
I am a newbie in angularjs
Thanks.
Well ! ng-show is not working here and the function is not getting called at all written in ng-show !
If i correctly understand you want to create a pagination :
So i am giving you a very simple solution of pagination using a pagination filter .
you need to add this filter to your app :
app.filter('pagination', function() {
return function(input, start) {
start = +start; //parse to int
if (input != undefined && Object.keys(input).length > 0) {
return input.slice(start);
}
}
});
In your html :
<tr ng-repeat="x in ProductInfo_Pager | pagination: currentPage * rowPerPage | limitTo: rowPerPage|orderBy :sortType:sortReverse | filter:searchText" ng-class="$even?'table-danger':'table-info'">
<td>{{$index+1}}</td>
<td>{{x.Product}}</td>
<td>{{x.Location}}</td>
<td>{{x.Qty}}</td>
<td>{{x.UnitPrice | currency : '₹':2}}</td>
<td class="text-center">
<i class="fa fa-flag" aria-hidden="true" style="color:red" /> |
<i class="fa fa-bolt" aria-hidden="true" style="color:red" /> |
<i class="fa fa-users" aria-hidden="true"></i>
</td>
</tr>
In your pagination ul below your table :
<ul class="pagination">
<li class="page-item" ng-repeat="x in getNumber(rowPerPage) track by
$index">
<a class="page-link" ng-click="pagerIndex=$index+1">{{$index+1}}
</a>
</li>
</ul>
in your controller :
$scope.numberOfPages = function() {
if ($scope.ProductInfo_Pager != undefined) {
return Math.ceil($scope.ProductInfo_Pager.length /
$scope.rowPerPage);
}
};
Hope it work ! if any doubt please let me know .

html not rendered in ng-template

I have some json with correct format that passed from laravel controller and i want to show them recursively with angular but the HTML inside ng-template not rendered. what's wrong?
note: I replaced the angular default tag {{ }} with <% %>
<div id="treeViewContent" ng-init="getTreeData()">
<script type="text/ng-template" id="directoryTree">
<div class="tree-item" ng-click="loadDir(dir.address)">
<i class="fa fa-folder orange"></i>
<% dir.name %>
</div>
<ul ng-if="dir.subdir">
<li ng-repeat="dir in dir.subdir" ng-include="'directoryTree'"></li>
</ul>
</script>
<ul class="noselect">
<li>
<div class="tree-item" ng-click="loadDir('/')">
<i class="fa fa-hdd-o blue"></i>
{{ ucfirst(\Auth::user()->username) }}
</div>
<ul>
<li ng-repeat="dir in dirs" ng-include="'directoryTree'"></li>
</ul>
</li>
</ul>
</div>
and getTreeData() is:
$scope.dirs = [];
$scope.getTreeData = function()
{
$http.post("/admin/drive/treeData", {_token: csrf_code}).then(function(response)
{
if (response.status == 200)
{
$scope.dirs = response.data;
}
else
{
Flash({status: "failed", message: "Error"});
}
})
}
and json data
[
{
"name":"image",
"address":"\/image",
"subdir":[
{
"name":"document",
"address":"\/image\/document",
"subdir":[
]
}
]
},
{
"name":"document",
"address":"\/document",
"subdir":[
]
},
{
"name":"movies",
"address":"\/movies",
"subdir":[
]
}
]
Please find the plunkr link plnkr.co/edit/B33ZhzU03CyS45a0lX4w?p=preview, the above code is working fine. Please check the json structure or post the json here.

ng-repeat shows another ng-repeat data

Hi i am trying to show up 2 menu's
Deparments -> subdepartments
List item
onclick of "event" button
should show up. onclick of "dates", button
should show up.
Here the issue is both the 1) and 2) display in single menu though both the htmls are different. Where am i going wrong.Below is the code.
HTML:
<div class="tab" >
<div class="sidebar-top">
<ul class="nav nav-pills nav-justified">
<li class="active">Event</li>
<li>Date</li>
</ul>
</div>
<div class="tab-content clearfix">
<div class="tab-pane active" id="1a">
<ul class="nav nav-sidebar">
<li class=" nav-active active"><i class="icon-home"></i><span>Dashboard</span></li>
<li class="nav-parent" ng-repeat="(key, value) in getdatewasedetails | groupBy: 'depatName'">
<i class="fa fa-link"></i><span></span>{{ key }} <span class="fa arrow"></span>
<ul class="children collapse" ng-repeat="subdept in value">
<li > {{ subdept.serviceName }} </li>
</ul>
</li>
</ul>
</div>
<div class="tab-pane" id="2a">
<ul class="nav nav-sidebar">
<li class=" nav-active active"><i class="icon-home"></i><span>Dashboard</span></li>
<li class="nav-parent" ng-repeat="(key, value) in getdatewasedetails| groupBy: 'month'">
<i class="fa fa-link"></i><span></span>{{ key | date:'MMMM' : 'UTC' }} <span class="fa arrow"></span>
<ul class="children collapse" ng-repeat="currDates in value">
<li > {{currDates.testDate | date:'longDate' : 'UTC'}} </li>
</ul>
</li>
</ul>
</div>
</div>
</div>
Resulted Json:
Angular JS:
$scope.lastVisit = function () {
var request = $http({
method: "get",
url: "dashboardServiceCall.php",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
/* Successful HTTP get request or not */
request.success(function (data, status, headers, config) {
z=0;
for(var x=0; x < data.length; x++){
if(data[x]['type'] == 3){
for(var g=0; g<data[x]['data']['dateWaseReportResForTests'].length; g++){
$scope.getdatewasedetails[z] = data[x]['data']['dateWaseReportResForTests'][g];
$scope.getdatewasedetails[z].testDate = new Date($scope.getdatewasedetails[z].testDate);
$scope.getdatewasedetails[z].category = data[x]['data']['panelName'];
$scope.getdatewasedetails[z].month = $scope.getdatewasedetails[z].testDate.getMonth();
z++;
}
for(var y=0; y<data[x]['data']['dateWaseReportResForGroups'].length; y++){
for(var d=0; d< data[x]['data']['dateWaseReportResForGroups'][y]['data']['dateWaseReportResForTests'].length; d++){
$scope.getdatewasedetails[z] = data[x]['data']['dateWaseReportResForGroups'][y]['data']['dateWaseReportResForTests'][d];
$scope.getdatewasedetails[z].testDate = new Date($scope.getdatewasedetails[z].testDate);
$scope.getdatewasedetails[z].category = data[x]['data']['panelName'];
$scope.getdatewasedetails[z].month = $scope.getdatewasedetails[z].testDate.getMonth();
z++;
}
}
}else if(data[x]['type'] == 1 ){
for(var g=0; g<data[x]['data']['dateWaseReportResForTests'].length; g++){
$scope.getdatewasedetails[z] = data[x]['data']['dateWaseReportResForTests'][g];
$scope.getdatewasedetails[z].testDate = new Date($scope.getdatewasedetails[z].testDate);
$scope.getdatewasedetails[z].category = data[x]['data']['dateWaseReportResForTests'][g]['serviceName'];
$scope.getdatewasedetails[z].month = $scope.getdatewasedetails[z].testDate.getMonth();
z++;
}
}else if(data[x]['type'] == 2){
for(var y=0; y<data[x]['data']['dateWaseReportResForGroups'].length; y++){
for(var d=0; d< data[x]['data']['dateWaseReportResForGroups'][y]['data']['dateWaseReportResForTests'].length; d++){
$scope.getdatewasedetails[z] = data[x]['data']['dateWaseReportResForGroups'][y]['data']['dateWaseReportResForTests'][d];
$scope.getdatewasedetails[z].testDate = new Date($scope.getdatewasedetails[z].testDate);
$scope.getdatewasedetails[z].category = data[x]['data']['dateWaseReportResForGroups'][y]['data']['groupName'];
$scope.getdatewasedetails[z].month = $scope.getdatewasedetails[z].testDate.getMonth();
z++;
}
}
}
}
$scope.leftNavMenu = $scope.getdatewasedetails;
});
}
Above two images show output.both the ng-repeats are rendering. i am not sure where am i going wrong.Any help would be great. thanks in advance.

How to add value to object from another object by click in Angular

I'm trying to create shopping cart, when clicking on one of the products its add to shoping cart.
So, I build an Object that contains all products, and another array that
will contain all clicked item.
When I'm trying to add the value of correct selected item from the products object i'm getting undefined.
var app = angular.module('myApp',[]); app.controller("myCtrl",function ($scope) {
$scope.products =
[
{ name: 'Apple', price: 5, img: '/Apple.jpg' },
{ name: 'Banana', price: 3.7, img: '/Banana.jpg' },
{ name: 'Grapes', price: 10 , img:'/Grapes.jpg' }
];
$scope.addProduct= function () {
$scope.products.push({name:$scope.nameProduct, price:$scope.priceProduct, tmuna:$scope.imgProduct});
$scope.nameProduct = "";
$scope.priceProduct = "";
$scope.imgProduct = "";
};
$scope.cartList = [{ name: 'Apple'}];
$scope.addToCart = function () {
$scope.cartList.push({name:$scope.nameProduct});
$scope.nameProduct = "";
};
});
<div class="dropdown pull-right">
<button class="btn btn-default dropdown-toggle" type="button" id="menu1" data-toggle="dropdown">
Shopping Cart <span class="glyphicon glyphicon-shopping-cart"></span>
<span class="caret"></span></button>
<ul class="dropdown-menu" role="menu" aria-labelledby="menu1" ng-repeat="product in cartList">
<li role="presentation"><a role="menuitem" tabindex="-1" >{{product.name}}</a></li>
</ul>
</div>
<form >
<p>Product: <input type = "text" ng-model = "nameProduct"></p>
<p>Price: <input type = "number" ng-model = "priceProduct"></p>
<p>Image: <input type = "text" ng-model = "imgProduct"></p>
<input type = "submit" value = "Add" ng-click = "addProduct()">
</form>
</div>
<div class="product" ng-repeat="product in products">
<img ng-src="{{product.img}}" />
<div class="name">{{product.name}}</div>
<div class="price">${{product.price}}</div>
<p class="badge" ng-click="addToCart()">Add to<span class="glyphicon glyphicon-shopping-cart"></span></p>
</div>
When you're calling addToCart() the function uses what's on $scope.nameProduct, but that's an empty string. You cleared it on addProduct() function.
Pass the name of the product you're adding:
ng-click="addToCart(product.name)"
And change your function accordingly:
$scope.addToCart = function (productName) {
$scope.cartList.push({ name: productName });
};
You need to pass the product object in the addToCart function like this:
https://jsfiddle.net/Lyrjp92z/
JS
$scope.addToCart = function(product) {
$scope.cartList.push({
name: product.name
});
};
HTML
<p class="badge" ng-click="addToCart(product)">Add to<span class="glyphicon glyphicon-shopping-cart"></span></p>
Also note, that passing in the product object and not just the string will allow you to also pass in the price, which you can calculate a total from.

How to get dynamic ng-model from ng-repeat in javascript?

I'm developoing a web app and stuck here:
Part of the HTML:
<div class="input-group">
<select name="select" class="form-control input-group-select" ng-options="key as key for (key , value) in pos" ng-model="word.pos" ng-change="addPos()">
<option value="">Choose a POS</option>
</select>
<span class="sort"><i class="fa fa-sort"></i></span>
</div>
<ul class="listGroup" ng-show="_pos.length > 0">
<li class="list" ng-repeat="item in _pos track by $index">
<span>
{{item.pos}}
<span class="btn btn-danger btn-xs" ng-click="delPos($index)">
<span class="fa fa-close"></span>
</span>
</span>
<!-- I wanna add the input which can add more list item to the item.pos-->
<div class="input-group">
<a class="input-group-addon add" ng-class=" word.newWordExp ? 'active' : ''" ng-click="addItemOne()"><span class="fa fa-plus"></span></a>
<input type="text" class="form-control exp" autocomplete="off" placeholder="Add explanation" ng-model="word.newWordExp" ng-enter="addExpToPos()">
{{word.newWordExp}}
</div>
</li>
</ul>
Part of the js:
$scope._pos = [];
$scope.addPos = function () {
console.log("You selected something!");
if ($scope.word.pos) {
$scope._pos.push({
pos : $scope.word.pos
});
}
console.dir($scope._pos);
//console.dir($scope.word.newWordExp[posItem]);
};
$scope.delPos = function ($index) {
console.log("You deleted a POS");
$scope._pos.splice($index, 1);
console.dir($scope._pos);
};
$scope.addItemOne = function (index) {
//$scope.itemOne = $scope.newWordExp;
if ($scope.word.newWordExp) {
console.log("TRUE");
$scope._newWordExp.push({
content: $scope.word.newWordExp
});
console.dir($scope._newWordExp);
$scope.word.newWordExp = '';
} else {
console.log("FALSE");
}
};
$scope.deleteItemOne = function ($index) {
$scope._newWordExp.splice($index, 1);
};
So, what am I wannt to do is select one option and append the value to $scope._pos, then display as a list with all of my selection.
And in every list item, add an input filed and add sub list to the $scope._pos value.
n.
explanation 1
explanation 2
explanation 3
adv.
explanation 1
explanation 2
So I don't know how to generate dynamic ng-model and use the value in javascript.
Normaly should like ng-model="word.newExplanation[item]" in HTML, but in javascript, $scope.word.newExplanation[item] said "item is not defined".
can any one help?
If I've understood it correclty you could do it like this:
Store your lists in an array of object this.lists.
The first object in the explanation array is initialized with empty strings so ng-repeat will render the first explanation form.
Then loop over it with ng-repeat. There you can also add dynamically the adding form for your explanation items.
You can also create append/delete/edit buttons inside the nested ng-repeat of your explanation array. Append & delete is already added in the demo.
Please find the demo below or in this jsfiddle.
angular.module('demoApp', [])
.controller('appController', AppController);
function AppController($filter) {
var vm = this,
explainTmpl = {
name: '',
text: ''
},
findInList = function (explain) {
return $filter('filter')(vm.lists, {
explanations: explain
})[0];
};
this.options = [{
name: 'option1',
value: 0
}, {
name: 'option2',
value: 1
}, {
name: 'option3',
value: 2
}];
this.lists = [];
this.selectedOption = this.options[0];
this.addList = function (name, option) {
var list = $filter('filter')(vm.lists, {
name: name
}); // is it in list?
console.log(name, option, list, list.length == 0);
//vm.lists
if (!list.length) {
vm.lists.push({
name: name,
option: option,
explanations: [angular.copy(explainTmpl)]
});
}
};
this.append = function (explain) {
console.log(explain, $filter('filter')(vm.lists, {
explanations: explain
}));
var currentList = findInList(explain);
currentList.explanations.push(angular.copy(explainTmpl));
}
this.delete = function (explain) {
console.log(explain);
var currentList = findInList(explain),
index = currentList.explanations.indexOf(explain);
if (index == 0 && currentList.explanations.length == 1) {
// show alert later, can't delete first element if size == 1
return;
}
currentList.explanations.splice(index, 1);
};
}
AppController.$inject = ['$filter'];
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" ng-controller="appController as ctrl">
<select ng-model="ctrl.selectedOption" ng-options="option.name for option in ctrl.options"></select>
<input ng-model="ctrl.listName" placeholder="add list name" />
<button class="btn btn-default" title="add list" ng-click="ctrl.addList(ctrl.listName, ctrl.selectedOption)"><i class="fa fa-plus"></i>
</button>
<div class="list-group">Debug output - current lists:<pre>{{ctrl.lists|json:2}}</pre>
<div class="list-group-item" ng-repeat="list in ctrl.lists">
<h2>Explanations of list - {{list.name}}</h2>
<h3>Selected option is: {{ctrl.selectedOption}}</h3>
<div class="list-group" ng-repeat="explain in list.explanations">
<div class="list-group-item">
<p class="alert" ng-if="!explain.title">No explanation here yet.</p>
<div class="well" ng-if="explain.title || explain.text">
<h4>
{{explain.title}}
</h4>
<p>{{explain.text}}</p>
</div>Title:
<input ng-model="explain.title" placeholder="add title" />Text:
<input ng-model="explain.text" placeholder="enter text" />
<button class="btn btn-primary" ng-click="ctrl.append(explain)">Append</button>
<button class="btn btn-primary" ng-click="ctrl.delete(explain)">Delete</button>
</div>
</div>
</div>
</div>
</div>

Resources