$watch ngModel from inside directive using isolate scope

You’ll need to watch a function that returns the $modelValue you’re watching. The following code shows a basic example: app.directive(‘myDirective’, function (){ return { require: ‘ngModel’, link: function(scope, element, attrs, ngModel) { scope.$watch(function () { return ngModel.$modelValue; }, function(newValue) { console.log(newValue); }); } }; }); Here’s a plunker of the same idea in action.

Shorthand for if-else statement

Using the ternary 😕 operator [spec]. var hasName = (name === ‘true’) ? ‘Y’ :’N’; The ternary operator lets us write shorthand if..else statements exactly like you want. It looks like: (name === ‘true’) – our condition ? – the ternary operator itself ‘Y’ – the result if the condition evaluates to true ‘N’ – …

Read more

Easiest way to convert month name to month number in JS ? (Jan = 01)

Just for fun I did this: function getMonthFromString(mon){ return new Date(Date.parse(mon +” 1, 2012″)).getMonth()+1 } Bonus: it also supports full month names 😀 Or the new improved version that simply returns -1 – change it to throw the exception if you want (instead of returning -1): function getMonthFromString(mon){ var d = Date.parse(mon + “1, 2012”); …

Read more

Scroll smoothly to specific element on page

Question was asked 5 years ago and I was dealing with smooth scroll and felt giving a simple solution is worth it to those who are looking for. All the answers are good but here you go a simple one. function smoothScroll(){ document.querySelector(‘.your_class or #id here’).scrollIntoView({ behavior: ‘smooth’ }); } just call the smoothScroll function …

Read more

Palindrome check in Javascript

Maybe I will suggest alternative solution: function checkPalindrom (str) { return str == str.split(”).reverse().join(”); } UPD. Keep in mind however that this is pretty much “cheating” approach, a demonstration of smart usage of language features, but not the most practical algorithm (time O(n), space O(n)). For real life application or coding interview you should definitely …

Read more

HTML-encoding lost when attribute read from input field

EDIT: This answer was posted a long ago, and the htmlDecode function introduced a XSS vulnerability. It has been modified changing the temporary element from a div to a textarea reducing the XSS chance. But nowadays, I would encourage you to use the DOMParser API as suggested in other anwswer. I use these functions: function …

Read more

Isotope v2 filtering with Infinite Scroll – Filter not finding all items and Window not resizing on filter

For question 2, one thing you could do is applying the display:none style to all hidden elements (and remove from all the visible ones) after isotope filtering. I think you should be able to use the “on layoutComplete” event listener of isotope to apply it at the right time, like this: $container.isotope( ‘on’, ‘layoutComplete’, function( …

Read more