AngularJS – Directives vs Controllers

Here’s a brief stand-alone answer, with links to official docs for further info (definition of “services” added for good measure): http://docs.angularjs.org/guide/controller In AngularJS, a controller is a JavaScript constructor function that is used to augment the AngularJS scope. When a controller is attached to the DOM via the ng-controller directive, AngularJS will instantiate a new … Read more

Dynamic class in Angular.js

You can simply assign a function as an expression and return proper class from there. Edit: there is also better solution for dynamic classes. Please see note below. Snippet from view: <div ng-class=”appliedClass(myObj)”>…</div> and in the controller: $scope.appliedClass = function(myObj) { if (myObj.someValue === “highPriority”) { return “special-css-class”; } else { return “default-class”; // Or … Read more

Highlighting a filtered result in AngularJS

In did that for AngularJS v1.2+ HTML: <span ng-bind-html=”highlight(textToSearchThrough, searchText)”></span> JS: $scope.highlight = function(text, search) { if (!search) { return $sce.trustAsHtml(text); } return $sce.trustAsHtml(text.replace(new RegExp(search, ‘gi’), ‘<span class=”highlightedText”>$&</span>’)); }; CSS: .highlightedText { background: yellow; }

AngularJS event on window innerWidth size change

We could do it with jQuery: $(window).resize(function(){ alert(window.innerWidth); $scope.$apply(function(){ //do something to update current scope based on the new innerWidth and let angular update the view. }); }); Be aware that when you bind an event handler inside scopes that could be recreated (like ng-repeat scopes, directive scopes,..), you should unbind your event handler when … Read more

Angularjs – Hide content until DOM loaded

In your CSS add: [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak { display: none !important; } and just add a “ng-cloak” attribute to your div like here: <div id=”template1″ ng-cloak>{{scoped_var}}<div> doc: https://docs.angularjs.org/api/ng/directive/ngCloak

How to ‘unwatch’ an expression

To have a repeater with a large array that you don’t watch to watch every item. You’ll need to create a custom directive that takes one argument, and expression to your array, then in the linking function you’d just watch that array, and you’d have the linking function programmatically refresh the HTML (rather than using … Read more