Angular toggling variable within ng-click not working - angularjs

I have a table that lists customers and for customers that also have a client list allows the user to click the table row to show that list. The HTML looks like this:
<tbody ng-repeat ="item in customers | clientSettingsFilter:customerId">
<tr ng-class="{'row-hover': item.clientSettings.length>0}" ng-click="item.showClients=!item.showClients">
<td><span ng-class="{true:'glyphicon glyphicon-chevron-down', false:'glyphicon glyphicon-chevron-right'}[item.showClients]" ng-hide="item.clientSettings.length==0"></span></td>
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td><button type="button" class="btn btn-default btn-xs" ng-click="go('/client-config/defaults/'+item.id)">Defaults</button></td>
</tr>
<tr ng-show="item.showClients">
..... // client data
The bizarre behavior I'm having is this:
If I leave the 'showClients' property undefined in the customers data set, everything works as expected, except that the chevron icon does not show at first. After clicking once, it shows up and the toggle works as expected. I was thinking this might be because the ng-class is looking for true or false, and undefined doesn't satisfy either of these.
If I pre-define the showClients property to either true or false, the chevron shows correctly on page load and the client list shows correctly, but the toggle no longer functions, as though ng-click is either not doing anything or for some reason is unable to change the value. I'm not sure how to debug an in-line directive like that.
EDIT
Per request, here is the relevent code from the controller:
filter('clientSettingsFilter', function () {
return function (customers, customerId) {
var filtered = [];
if (!customerId)
return filtered;
customerId = customerId.toLowerCase();
angular.forEach(customers, function (item) {
if (item.id.toLowerCase().indexOf(customerId) !== -1) {
// format some text properties, omitted for brevity
// if this line is uncommented, the ng-click does not work
//item.showClients = false;
filtered.push(item);
}
});
return filtered;
};
});

The conditional you are using in ng-class will only add something when value is either true or false, not when it's undefined.
Instead use the more verbose ternary operator:
ng-class="item.showClients ? 'glyphicon-chevron-down' : 'glyphicon-chevron-right'"
And might as well move the class glyphicon to the ordinary class attribute:
class="glyphicon"
Demo: http://plnkr.co/edit/bxgp4HyFkOygc0foxAKN?p=preview
The behavior you are witnessing when uncommenting item.showClients = false; in your filter is due to how the digest loop works.
If item.showClients is false and you click the tr the following will happen (a bit simplified):
The expression in ng-click will execute, setting item.showClients to true
The digest loop will start
The filter will run and set item.showClients to false again
Filters are meant for filtering, not for modification.
Also note that when using a filter with ng-repeat it will fire each digest cycle, and as each digest loop consists of multiple digest cycles (minimum of two) it's important to keep filters simple or they will have a bad impact on performance.

Related

Multiple directives in same element operating on visibility

I have been struggling with my approach for the following scenario.
I have a custom directive authorize where I pass the name of a group. If the current user has this group in his profile then the element will be visible, if not the element will be hidden.
Example:
<button class="btn btn-default" role="button"
ng-click="myVm.edit()"
authorize="{{myVm.groupName}}"><!--groupName = "accountants"-->
<span class="fa fa-edit" aria-hidden="true"></span> Edit
</button>
and my original directive in typescript authorize.ts using the link function (because I operate on the DOM)
namespace app.blocks.directives {
"use strict";
class AuthorizeDirective implements ng.IDirective {
public restrict: string = "A";
public replace: boolean = true;
constructor(private $compile: ng.ICompileService, private authService: services.IAuthService) {
}
public static factory(): ng.IDirectiveFactory {
const directive = ($compile: ng.ICompileService, authService: services.IAuthService) =>
new AuthorizeDirective($compile, authService);
directive.$inject = [
"$compile",
"app.services.AuthService"
];
return directive;
}
public link(scope: ng.IScope, instanceElement: ng.IAugmentedJQuery, instanceAttributes: ng.IAttributes): void {
let groupName: string = (<any>instanceAttributes).authorize;
let element = angular.element(instanceElement);
let hasGroup: boolean = this.authService.hasGroup(groupName);
element.attr("ng-show", String(hasGroup));
//remove the attribute, otherwise it creates an infinite loop.
element.removeAttr("authorize");
this.$compile(element)(scope);
}
}
}
angular
.module("app.blocks.directives")
.directive("authorize", AuthorizeDirective.factory());
}
This is working fine, the button is hidden if the authService returns false because the user does not belong to that group (i.e: "accountants").
The problem appears when my DOM element has ng-show or ng-hide directives also. Example:
<button class="btn btn-default" role="button"
ng-hide="myVm.isDeleted"
ng-click="myVm.edit()"
authorize="{{myVm.groupName}}">
<!--groupName = "accountants"-->
<span class="fa fa-edit" aria-hidden="true"></span> Edit
</button>
When myVm.isDeleted = true it seems that overrides the result of my directive and the DOM element is displayed (when it shouldn't because the user does not belong to the specified group as per my authorize directive).
I realize there is some priority (by default 0) in directives, when two directives have the same priority they are executed in alphabetical order according to the documentation. This post was very helpful to understand that.
So I have some options here:
Have my authorize directive evaluate the conditional in ng-hide or ng-show in order to compute (i.e: if the ng-hide says that the element should be shown but the user has not the specific group, then the element should be hidden). I could not find a way to access myVm.isDeleted within my directive link's function. If anyone know how I'd be happy with this approach.
Have my authorize directive executed BEFORE any other directive and rely on angular to later on determine visibility according to ng-show or ng-hide (i.e: if my authorize directive determines that the element should be hidden because the user does not belong to the given group, then it should transform the DOM element and make it ng-show="false" for example, so that angular hides the element later on. This approach does not seem to work, the DOM seems correct, I can see that the button has ng-show="false" but for some reason I still see the button on screen so it's as if Angular didn't know that it has to hide that element. The funny thing is that if I move to another tab, and I go back to the same tab (the view is reloaded and the directive re-executed) then it works fine. What's going on?.
I went with the option 2 and this is the code that seems to work properly manipulating the DOM, but Angular does not apply the ng-show directive afterwards therefor the result is not as expected.
public priority: number = 999; //High priority so it is executed BEFORE ng-show directive
public link(scope: ng.IScope, instanceElement: ng.IAugmentedJQuery, instanceAttributes: ng.IAttributes): void {
let groupName: string = (<any>instanceAttributes).authorize;
let element = angular.element(instanceElement);
let ngShow: string = (<any>instanceAttributes).ngShow;
let ngHide: string = (<any>instanceAttributes).ngHide;
let hasGroup: boolean = this.authService.hasGroup(groupName);
let ngHideValue = ngHide ? "!" + ngHide : "";
let ngShowValue = ngShow ? ngShow : "";
//if hasGroup, use whatever ng-show or ng-hide value the element had (ng-show = !ng-hide).
//if !hasGroup, it does not matter what value the element had, it will be hidden.
if (hasGroup) {
element.attr("ng-show", (ngShowValue + ngHideValue) || "true");
} else {
element.attr("ng-show", "false");
}
element.removeAttr("ng-hide");
//remove the attribute, otherwise it creates an infinite loop.
element.removeAttr("authorize");
this.$compile(element)(scope);
}
I'd argue that seeing as your authorize directive basically just controls whether the element that it's placed displays or not, you should just move its logic out into a service that you inject into your controller, and let ng-hide control whether the element displays like it's designed to.
This will be easier for developers who come later to understand - no one wants to go drilling down into individual directives to find various scattered bits of code that call the server, and your button then just looks like this:
<button class="btn btn-default" role="button"
ng-hide="myVm.isDeleted || !myVm.isAuthorized(myVm.groupName)"
ng-click="myVm.edit()">
<span class="fa fa-edit" aria-hidden="true"></span> Edit
</button>
Nice and simple to read.

AngularJS : why after loading more data filter stop working?

there is one filter functionality in my demo I will explain my problem I have one table in which i use infinite scroll is implemented In other words when user moves to bottom it load more data.There is search input field in top .Using this I am able to filter item in table .but I don't know why it is not working
When you search "ubs" and "ing" first time .it works perfectly .But when you load more data other words when user scroll to bottom and load more data the again it try to filter "ubs" and "ing" it not give any result why ?
<label class="item item-input">
<img src="https://dl.dropboxusercontent.com/s/n2s5u9eifp3y2rz/search_icon.png?dl=0">
<input type="text" placeholder="Search" ng-model="query">
</label>
secondly Actually I am implementing infinite scroll so only 100 element display .can we search element from 2000 (which I am getting from service )and display data the search result ?
Update :
Here's a Plunker with everything working together. I have separated all of the pieces into individual JS files, as it was getting unruly:
Plunker
Search
The built in filter will only return results from the current view data that the ng-repeat is displaying. Because you're not loading all of the data into the view at once, you'll have to create your own search functionality.
In the demo, click the search icon to show the search box, then type your search value and press the ENTER key or click the search button to return the results.
Since you want to check whether the user pressed ENTER you have to pass both the event and the querystring to the function, so you can check for the enter keycode. The function should also run when someone clicks or taps the search button. I set ng-model="query" on the input, so query is the reference in the view. Therefore, you'll add ng-click="searchInvoices($event, query)" to your search button, and ng-keyup="searchInvoices($event, query)" to the input. And, finally, to make it easy to clear the input field, add a button that displays when the input is not empty with ng-show="query" and attach a click event with ng-click="query=null; resetGrid()".
Add the searchInvoices function to your controller. It will only run the search if either the query is empty (because you need to reset the view if the person uses the backspace key to empty the input) OR if the user pressed ENTER OR if the event was a click event in case the user clicks the search button. The inner if statement, prevents the search from running if the query is empty and just resets the view. If the query is not empty, against the total dataset and builds an array of matching results, which is used to update the view.
The last line sets the scroll position to the top of the scrollview container. This makes sure that the user sees the results without having to click somewhere in the scrollview container. Make sure you inject the $ionicScrollDelegate into your controller for this to work and set delegate-handle="invoicegrid" on your ion-scroll directive.
$scope.searchInvoices = function(evt, queryval) {
if (queryval.length === 0 || evt.keyCode === 13 || evt.type === 'click') {
if (queryval.length === 0) {
$scope.invoice_records = $scope.total_invoice_records;
} else {
var recordset = $scope.total_invoice_records;
results = [];
var recordsetLength = recordset.length;
var searchVal = queryval.toLowerCase();
var i, j;
for (i = 0; i < recordsetLength; i++) {
var record = recordset[i].columns;
for (j = 0; j < record.length; j++) {
var invoice = record[j].value.toLowerCase();
if (invoice.indexOf(searchVal) >= 0) {
results.push(recordset[i]);
}
}
}
$scope.invoice_records = results;
$ionicScrollDelegate.$getByHandle('invoicegrid').scrollTop();
}
}
};
Lastly, you need to modify the loadMore() function that is used by the infinite scroll directive, so that it doesn't try to load additional data when scrolling through the search results. To do this, you can just pass the query into loadMore on the directive like: on-infinite="loadMore(query)", then in your function, you can just run the broadcast event when the query exists. Also, removing the ngIf will ensure that the list remains dynamic.
$scope.loadMore = function(query) {
if (query || counter >= $scope.total_invoice_records.length) {
$scope.$broadcast('scroll.infiniteScrollComplete');
} else {
$scope.counter = $scope.counter + showitems;
$scope.$broadcast('scroll.infiniteScrollComplete');
}
};
You used filter in wrong way inside ng-repeat like ng-repeat="column in invoice_records | filter:query" instead of ng-repeat="column in invoice_records | query"
<div class="row" ng-repeat="column in invoice_records |filter:query">
<div class="col col-center brd collapse-sm" ng-repeat="field in column.columns" ng-show="data[$index].checked && data[$index].fieldNameOrPath===field.fieldNameOrPath">{{field.value}}</div>
<div class="col col-10 text-center brd collapse-sm"></div>
</div>
Demo Plunkr

Change Single Button Color from ngRepeat generated button list

I'm using ngRepeat to generate four buttons. Whenever I click one of the buttons, I want to change its color and also execute a function (for now, I'm just using console.log for sake of simplicity). If I click on another button, I want to change its color while reverting the previous button back to its original color.
I have a couple of issues - the first is that I can't seem to get ng-click to accept two commands (the first being the console.log function and the second being the instruction to change the button color). The other issue is that if I take out the console.log function, I end up changing all of the buttons when I click on one.
Any ideas? Here's the plunkr: http://plnkr.co/edit/x1yLEGNOcBNfVw2BhbWA. You'll see the console.log works but the button changing doesn't work. Am I doing something wrong with this ng-click?
<span class="btn cal-btn btn-default" ng-class="{'activeButton':selectedButt === 'me'}" ng-click="log(element);selectedButt = 'me'" data-ng-repeat="element in array">{{element}}</span>
You can create a simple function in your controller which handles this logic:
$scope.selectButton = function(index) {
$scope.activeBtn = index;
}
Then, you can simply check in your template if the current button is active:
<span class="btn cal-btn btn-default" ng-class="{true:'activeButton'}[activeBtn == $index]" ng-click="selectButton($index);" ng-repeat="element in array">{{element}}</span>
I also changed your plunkr
You may convert your element list from string array to object array first.
$scope.array = [
{"name":"first", "checked":false},
{"name":"second", "checked":false},
{"name":"third", "checked":false},
{"name":"fourth", "checked":false}
];
And your log function need to change to:
$scope.log = function(element) {
console.log(element.name);
angular.forEach($scope.array, function(elem) {
elem.checked = false;
});
element.checked = !element.checked;
}
Then, in your HTML:
<button class="btn cal-btn"
ng-repeat="element in array"
ng-click="log(element)"
ng-class="{activeButton: element.checked, 'btn-default': !element.checked}"
>{{element.name}}</button>
Please see the updated plunker here.

filter and unfilter on ng-click with buttons

hello i have a couple of buttons i want to filter data with, but i can't figure out how to make it unfilter when i click the button again. I use the normal filtering expression like:
<tr ng-repeat='ledata in datas | filter:thecondition'></tr>
where the thecondition may vary depending on the button clicked, the button's code is the following
ng-click="thecondition = {type: 1}"
also how can i mark it with ng-class? make the button look pressed? thanks.
My recommendation is that try to implementing your own custom filter.
Something close to:
custom filter:
angular.module('myApp', []).filter('myFilter', function() {
return function(items, param1, param2) {
return items.filter(function(item){ /* your custom conditions */ });
};
});
and in your html
<li ng-repeat="item in items | myFilter:'car': 2">
Of course you could extend and perform the actions that are more suited to your app needs.
The reason why I recommend the custom filter is because it will allow you a better separation from the view and the business logic; which is more aligned with the MVVM design pattern behind angular.
For toggling the filter, try this:
ng-click="thecondition = thecondition ? '' : {type: 1}"
The ternary operator will set thecondition to an empty string if it has a value, and to the object with type : 1 if it's empty.
To set the class with ng-class, try this:
ng-class="{depressed_button: thecondition}"
When thecondition is truthy, the class depressed_button will be applied. It's up to you to define the depressed_button class in a stylesheet or elsewhere.

How to expand/collapse all rows in Angular

I have successfully created a function to toggle the individual rows of my ng-table to open and close using:
TestCase.prototype.toggle = function() {
this.showMe = !this.showMe;
}
and
<tr ng-repeat="row in $data">
<td align="left">
<p ng-click="row.toggle();">{{row.description}}</p>
<div ng-show="row.showMe">
See the plunkr for more code, note the expand/collapse buttons are in the "menu".
However, I can't figure out a way to now toggle ALL of the rows on and off. I want to be able to somehow run a for loop over the rows and then call toggle if needed, however my attempts at doing so have failed. See them below:
TestCase.prototype.expandAllAttemptOne = function() {
for (var row in this) {
if (!row.showMe)
row.showMe = !row.showMe;
}
}
function expandAllAttemptOneTwo(data) {
for (var i in data) {
if (!data[i].showMe)
data[i].showMe = !data[i].showMe;
}
}
Any ideas on how to properly toggle all rows on/off?
Using the ng-show directive in combination with the ng-click and ng-init directives, we can do something like this:
<div ng-controller="TableController">
<button ng-click="setVisible(true)">Show All</button>
<button ng-click="setVisible(false)">Hide All</button>
<ul>
<li ng-repeat="person in persons"
ng-click="person.visible = !person.visible"
ng-show="person.visible">
{{person.name}}
</li>
</ul>
</div>
Our controller might then look like this:
myApp.controller('TableController', function ($scope) {
$scope.persons = [
{ name: "John", visible : true},
{ name: "Jill", visible : true},
{ name: "Sue", visible : true},
{ name: "Jackson", visible : true}
];
$scope.setVisible = function (visible) {
angular.forEach($scope.persons, function (person) {
person.visible = visible;
});
}
});
We are doing a couple things here. First, our controller contains an array of person objects. Each one of these objects has a property named visible. We'll use this to toggle items on and off. Second, we define a function in our controller named setVisible. This takes a boolean value as an argument, and will iterate over the entire persons array and set each person object's visible property to that value.
Now, in our html, we are using three angular directives; ng-click, ng-repeat, and ng-show. It seems like you already kinda know how these work, so I'll just explain what I'm doing with them instead. In our html we use ng-click to set up our click event handler for our "Show All" and "Hide All" buttons. Clicking either of these will cause setVisible to be called with a value of either true or false. This will take care of toggling all of our list items either all on, or all off.
Next, in our ng-repeat directive, we provide an expression for angular to evaluate when a list item is clicked. In this case, we tell angular to toggle person.visible to the opposite value that it is currently. This effectively will hide a list item. And finally, we have our ng-show directive, which is simply used in conjunction with our visible property to determine whether or not to render a particular list item.
Here is a plnkr with a working example: http://plnkr.co/edit/MlxyvfDo0jZVTkK0gman?p=preview
This code is a general example of something you might do, you should be able to expand upon it to fit your particular need. Hope this help!

Resources