Posts

Showing posts with the label Angularjs

Angular Grid Ag-grid ColumnDefs Dynamically Change

Answer : In ag-grid the columns in gridOptions are used once at grid initialisation. If you change the columns after initialisation, you must tell the grid. This is done by calling gridOptions.api.setColumnDefs() Details of this api method are provided in the ag-grid documentation here. I think this has been fixed already. I am able to do something like this now with latest angular and ag-grid. Please note I am using ngxs here, however this still indicates the ability to get the column definitions async as I am getting the column defs based on the property names of the data that is being returned from the back-end in this case rowData. Firstly, I am fetching the row data from the back-end API. Then when it is fetched I perform operations in the Select for column that map the headers from returned data to properties. The data will not be displayed without headers, as soon as the headers are there it will redraw the grid with all the column definitions and data. <ag-grid...

Angular-UI Tabs: Add Class To A Specific Tab

Answer : I'm not sure that you can apply ng-class to tabs like that. After trying and failing I decided to look at the bootstrap-ui source for tabs and made an interesting discovery related to the tab heading attribute. Apparently you can put html in the heading section if you place the tab-heading as a child to a tab element. Check out the tabheading directive in here. This is the example they show: <tabset> <tab> <tab-heading><b>HTML</b> in my titles?!</tab-heading> And some content, too! </tab> <tab> <tab-heading><i class="icon-heart"></i> Icon heading?!?</tab-heading> That's right. </tab> </tabset> In your case I think you might be able to do something like this to get the same effect: <tab ng-repeat="tab in tabs" active="tab.active"> <tab-heading>{{tab.title}} <span ng-show="tab.new">new<...

Angular-ui-router: Ui-sref-active And Nested States

Answer : Instead of this- <li ui-sref-active="active"> <a ui-sref="posts.details">Posts</a> </li> You can do this- <li ng-class="{active: $state.includes('posts')}"> <a ui-sref="posts.details">Posts</a> </li> Currently it doesn't work. There is a discussion going on here (https://github.com/angular-ui/ui-router/pull/927) And, it will be added soon. UPDATE: For this to work, $state should be available in view. angular.module('xyz').controller('AbcController', ['$scope', '$state', function($scope, $state) { $scope.$state = $state; }]); More Info UPDATE [2]: As of version 0.2.11 , it works out of the box. Please check the related issue: https://github.com/angular-ui/ui-router/issues/818 Here's an option for when you are nesting multiple states that are not hierarchically related and you don't have a controller ava...

Can You Resolve An Angularjs Promise Before You Return It?

Answer : Short answer: Yes, you can resolve an AngularJS promise before you return it, and it will behave as you'd expect. From JB Nizet's Plunkr but refactored to work within the context of what was originally asked (i.e. a function call to service) and actually on site. Inside the service... function getSomething(id) { // There will always be a promise so always declare it. var deferred = $q.defer(); if (Cache[id]) { // Resolve the deferred $q object before returning the promise deferred.resolve(Cache[id]); return deferred.promise; } // else- not in cache $http.get('/someUrl', {id:id}).success(function(data){ // Store your data or what ever.... // Then resolve deferred.resolve(data); }).error(function(data, status, headers, config) { deferred.reject("Error: request returned status " + status); }); return deferred.promise; } Inside the ...

Angular 1.6.0: "Possibly Unhandled Rejection" Error

Answer : Try adding this code to your config. I had a similar issue once, and this workaround did the trick. app.config(['$qProvider', function ($qProvider) { $qProvider.errorOnUnhandledRejections(false); }]); The code you show will handle a rejection that occurs before the call to .then . In such situation, the 2nd callback you pass to .then will be called, and the rejection will be handled. However , when the promise on which you call .then is successful, it calls the 1st callback. If this callback throws an exception or returns a rejected promise, this resulting rejection will not be handled , because the 2nd callback does not handle rejections in cause by the 1st. This is just how promise implementations compliant with the Promises/A+ specification work, and Angular promises are compliant. You can illustrate this with the following code: function handle(p) { p.then( () => { // This is never caught. throw new Error(...

Angular.js Ng-repeat Filter By Property Having One Of Multiple Values (OR Of Values)

Answer : Best way to do this is to use a function: <div ng-repeat="product in products | filter: myFilter"> $scope.myFilter = function (item) { return item === 'red' || item === 'blue'; }; Alternatively, you can use ngHide or ngShow to dynamically show and hide elements based on a certain criteria. For me, it worked as given below: <div ng-repeat="product in products | filter: { color: 'red'||'blue' }"> <div ng-repeat="product in products | filter: { color: 'red'} | filter: { color:'blue' }"> I thing ng-if should work: <div ng-repeat="product in products" ng-if="product.color === 'red' || product.color === 'blue'">

Create Row Every After 2 Item In Angular Ng-repeat - Ionic Grid

Answer : I managed to do it using $even . <div ng-repeat="number in numbers"> <div class="row" ng-if="$even"> <div class="col col-50">{{numbers[$index]}}</div> <div class="col col-50">{{numbers[$index + 1]}}</div> </div> </div> Here's a working JSFiddle. The solution from @Patrick Reck is excellent, but it forces you to repeat your code twice, I suggest this improvement: <div ng-repeat="number in numbers"> <div class="row" ng-if="$even"> <div class="col col-50" ng-repeat="num in [numbers[$index],numbers[$index + 1]]"> {{num}} </div> </div> </div> this way you will write your code one time as if it is a normal ng-repeat You can add flex-wrap: wrap to class row http://jsfiddle.net/0momap0n/99/ ...

Angular JS: What Is The Need Of The Directive’s Link Function When We Already Had Directive’s Controller With Scope?

Image
Answer : After my initial struggle with the link and controller functions and reading quite a lot about them, I think now I have the answer. First lets understand , How do angular directives work in a nutshell: We begin with a template (as a string or loaded to a string) var templateString = '<div my-directive>{{5 + 10}}</div>'; Now, this templateString is wrapped as an angular element var el = angular.element(templateString); With el , now we compile it with $compile to get back the link function. var l = $compile(el) Here is what happens, $compile walks through the whole template and collects all the directives that it recognizes. All the directives that are discovered are compiled recursively and their link functions are collected. Then, all the link functions are wrapped in a new link function and returned as l . Finally, we provide scope function to this l (link) function which further executes the wrapped link functions ...

Adding Http Headers To Window.location.href In Angular App

Answer : When you use $window.location.href the browser is making the HTTP request and not your JavaScript code. Therefore, you cannot add a custom header like Authorization with your token value. You could add a cookie via JavaScript and put your auth token there. The cookies will automatically be sent from the browser. However, you will want to review the security implications of using a cookie vs. a header. Since both are accessible via JavaScript, there is no additional attack vector there. Unless you remove the cookie after the new page loads, there may be a CSRF exploit available. This answer is NOT a safe way, as the token is exposed in the URL, which is logged in browser history, access logs, etc. Use a domain cookie instead. I'll leave the answer as it can be an easy way to debug in your local setup. I am using JWT as authentication on a Laravel PHP backend, and it works by putting ?token=... in the URL. For example, when using AngularJS with satellizer plug...

Angular Ng-if="" With Multiple Arguments

Answer : It is possible. <span ng-if="checked && checked2"> I'm removed when the checkbox is unchecked. </span> http://plnkr.co/edit/UKNoaaJX5KG3J7AswhLV?p=preview For people looking to do if statements with multiple 'or' values. <div ng-if="::(a || b || c || d || e || f)"><div> Just to clarify, be aware bracket placement is important! These can be added to any HTML tags... span, div, table, p, tr, td etc. AngularJS ng-if="check1 && !check2" -- AND NOT ng-if="check1 || check2" -- OR ng-if="(check1 || check2) && check3" -- AND/OR - Make sure to use brackets Angular2 + *ngIf="check1 && !check2" -- AND NOT *ngIf="check1 || check2" -- OR *ngIf="(check1 || check2) && check3" -- AND/OR - Make sure to use brackets It's best practice not to do calculations directly within ngIfs, so assign the variables within yo...

Angular/Material Mat-form-field Input - Floating Label Issues

Answer : assuming you are using latest stable version of material 2, you can use floatLabel="never" to force label to not to float. here is live working demo this is clear in documentation https://material.angular.io/components/form-field/api <form class="search-form"> <mat-form-field class="example-full-width" appearance="standard"> <input class="toolbar-search" type="text" matInput> <mat-placeholder>Search</mat-placeholder> <mat-icon matSuffix style="font-size: 1.2em">search</mat-icon> </mat-form-field> </form> Please set the appearance of mat-form-field to standard and the placeholder will stop behaving like label. Explanation : By default the mat-label in mat-form-field floats and the appearance of mat-form-field is "legacy". That means if a mat-label is not present with the form field then placeholder will start behavin...

Angular UI Bootstrap Vertical Tabs

Answer : Another solution is to create something like this <div class="row"> <div class="col-sm-3"> <ul class="nav nav-tabs nav-stacked nav-pills" role="tablist"> <li ng-class="{'active': view_tab == 'tab1'}"> <a class="btn-lg" ng-click="changeTab('tab1')" href="">My Tab 1</a> </li> <li ng-class="{'active': view_tab == 'tab2'}"> <a class="btn-lg" ng-click="changeTab('tab2')" href="">My Tab 2</a> </li> </ul> </div> <div class="col-sm-9"> <div class="tab-content"> <div class="tab-pane" ng-show="view_tab == 'tab1'"> This is tab 1 content </div> <div class="tab-p...

Cannot Get Textarea Value In Angularjs

Answer : Your problem lies in the ui-if part. Angular-ui creates a new scope for anything within that directive so in order to access the parent scope, you must do something like this: <textarea ng-model="$parent.noticeText"></textarea> Instead of <textarea ng-model="noticeText"></textarea> This issue happened to me while not using the ng-if directive on elements surrounding the textarea element. While the solution of Mathew is correct, the reason seems to be another. Searching for that issue points to this post, so I decided to share this. If you look at the AngularJS documentation here https://docs.angularjs.org/api/ng/directive/textarea , you can see that Angular adds its own directive called <textarea> that "overrides" the default HTML textarea element. This is the new scope that causes the whole mess. If you have a variable like $scope.myText = 'Dummy text'; in your controller and bind that to...

Angular Http - ToPromise Or Subscribe

Answer : If you like the reactive programming style and want to be consistent within your application to always use observables even for single events (instead of streams of events) then use observables. If that doesn't matter to you, then use toPromise() . One advantage of observables is, that you can cancel the request. See also Angular - Promise vs Observable I think as long as the response is not a data stream that you're going to use, then you'd better use the .toPromise() approach, because it's meaningless to keep listening to a response that you don't need and it's not even going to change.

Create A Simple Bootstrap Yes/No Confirmation Or Just Notification Alert In AngularJS

Answer : so create a reusable service for that... read here code here: angular.module('yourModuleName').service('modalService', ['$modal', // NB: For Angular-bootstrap 0.14.0 or later, use $uibModal above instead of $modal function ($modal) { var modalDefaults = { backdrop: true, keyboard: true, modalFade: true, templateUrl: '/app/partials/modal.html' }; var modalOptions = { closeButtonText: 'Close', actionButtonText: 'OK', headerText: 'Proceed?', bodyText: 'Perform this action?' }; this.showModal = function (customModalDefaults, customModalOptions) { if (!customModalDefaults) customModalDefaults = {}; customModalDefaults.backdrop = 'static'; return this.show(customModalDefaults, customModalOptions); }; this.show = function (customModalDefaults, customModalOptions) { //Create temp objects t...

Angular JS Break ForEach

Image
Answer : The angular.forEach loop can't break on a condition match. My personal advice is to use a NATIVE FOR loop instead of angular.forEach . The NATIVE FOR loop is around 90% faster then other for loops. USE FOR loop IN ANGULAR: var numbers = [0, 1, 2, 3, 4, 5]; for (var i = 0, len = numbers.length; i < len; i++) { if (numbers[i] === 1) { console.log('Loop is going to break.'); break; } console.log('Loop will continue.'); } There's no way to do this. See https://github.com/angular/angular.js/issues/263. Depending on what you're doing you can use a boolean to just not going into the body of the loop. Something like: var keepGoing = true; angular.forEach([0,1,2], function(count){ if(keepGoing) { if(count == 1){ keepGoing = false; } } }); please use some or every instances of ForEach, Array.prototype.some: some is much the same as forEach but it break when the callback returns true Array.prototype.e...