Components - m-kostira/angularjs-notes GitHub Wiki

https://docs.angularjs.org/guide/component https://docs.angularjs.org/guide/component#example-of-a-component-tree

A component binds a controller and a template and has isolate scope:

'In order to make the definition easier, components enforce best practices like use of controllerAs, bindToController. They always have isolate scope and are restricted to elements.'

bindToController - binds scope properties directly to the controller. E.g. if the component's html element has an attribute foo=10, angular will create a property on the controller foo with a value 10.

controllerAs - the scope property name that the controller will be assigned to, defaults to $ctrl. I.e., you can use $ctrl in the template to reference the controller


Passing data in and out of the controller

Passing Objects:

Parent template:

<tr ng-repeat="mo in vm.managedObjects">
  <td><managed-object object="mo" /></td>
</tr>

Component template for :

<div>
    Managed Object id: {{vm.object.id}}
</div>

Component controller for :

(() => {
  'use strict';

  angular.module('managedObjectBrowser').component('managedObject', {
    templateUrl: ':::PLUGIN_PATH:::/components/managedObject.html',
    bindings: {
      object: '<'
    },
    controllerAs: 'vm',
    controller: Controller
  });

  /* @ngInject */
  function Controller() {
    var self = this;

    this.getDetails = getDetails;

    function getDetails() {
      return JSON.stringify(self.object, null, 2);
    }
  }

})();

Passing Strings:

Use @ in the bindings and {{}} in the templates.


The “&” binding

https://thinkster.io/egghead/isolate-scope-am

The “&” operator allows you to invoke or evaluate an expression on the parent scope of whatever the directive is inside of.

With, this, it is possible to pass data into a scoped method within the template.


app.directive("phone", function () {
  return {
    scope: {
      dial: "&"
    },
    template: '<input type="text" ng-model="value">' +
      '<div class="button" ng-click="dial({message:value})">' +
      'Call home!</div>',
  };
});
    <div phone dial="callHome(message)"></div>

TODO examples

⚠️ **GitHub.com Fallback** ⚠️