AngularJS Directives: an Aide Memoir

14 September 2015By Rich @Black Sand Solutions
  • AngularJS

I forget how to do things in directives life all the time. This post is an attempt to remember some of them.

Angular Directives : An Aide Memoir

I forget how to do things in directives life all the time.
This post is an attempt to remember some of them - or at least somewhere I can come to find them.

Get The Body Element
var body = angular.element($document[0].body);
Get An Element By Class
element[0].getElementsByClassName('fileselect');
Get An Element By Id
angular.element(document.querySelector('#theInput'));
Using Ng-Class
<li ng-class='{class : expression}'>
<li ng-class='{'class-name' : expression}'>
<li ng-class='{true: 'classOne', false: 'classTwo'}[expression]'>
Use The Ternary Operator In Ng-Class
<li ng-class='$first ? 'firstRow' : 'nonFirstRow''>
Access the FormController
require: '^form',

Then it will be available as the 4th argument in the link function:

link: function(scope, element, attrs, formCtrl) {
    console.log(formCtrl);
}
Access The ModelController
require: 'ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
     console.log(ngModelCtrl);
}
Access Model And Form Controller
require: ['^form','ngModel'],
link: function(scope, element, attrs, ctrls) {
     var form = ctrls[0];
     var ngModel = ctrls[1];
}
Use Model Passed In
<div ng-app="MyApp" ng-controller="MyCtrl">
    {{foo}}
    <my-directive ng-model="foo" />
</div>


var myApp = angular.module('MyApp', []);

myApp.controller('MyCtrl', function ($scope) {
    $scope.foo = "I'm foo!";
});

myApp.directive('myDirective', function () {
    return {
        restrict: 'AE',
        template: '<div><input type="text" ng-model="ngModel" /></div>',
        replace: true,
        scope: {
            ngModel : '=',
        },
    };
});
Watch Scope Variable Within Directive
      return {
        restrict: 'E',        
        scope: {
          ngModel : '='
        },
       link: function(scope, element, attrs) {

          scope.$watch('ngModel', function() {
           scope.state.isEmpty = (scope.ngModel == undefined);
         });
      }

See Also

Check if Attribute exists on directive
scope:{},
link: function(scope, element, attrs){
  scope.status = 'status' in attrs;
},

Pass Param to functions in expressions specified in the directive's attributes

<div ng-controller="MyCtrl">
    <div ng-repeat="item in items" my-component isolated-expression-foo="updateItem(item,temp)">
        {{item|json}}
    </div>
</div>


var myModule = angular.module('myModule', [])
    .directive('myComponent', function () {
        return {
            restrict:'A',
            scope:{
                isolatedExpressionFoo:'&'
            },
            link:function(scope,element,attr) {
                scope.isolatedExpressionFoo({temp:"some value"});
            }
        };
    })
    .controller('MyCtrl', ['$scope', function ($scope) {        
        $scope.items=[{id:1,value:"test"},{id:2,value:"TEst2"}];
        $scope.updateItem = function (item,temp) {
            console.log("Item param "+item.id);
            console.log("temp param " + temp);
        }
    }]);

Courtesy of SO

All Posts