JavaScript

Web-components like AngularJS directives

Posted on by  
Richard Rijnberk

As you may already know web components consist out of a set of technologies which are combined to create a custom element for use in your HTML markup. The main additions, as described in several blogposts, are HTML imports, Shadow Dom and Templates combined with isolated scripts and styling. (If these concepts are new to you i suggest you read up on web components at WebComponents.org). This blog post has a living example on plnkr.co. If we look at Angular it already supports html imports and isolated scripts through it's directive approach. This means we can already create custom components by using directives. The downside of this approach however is that there is no true isolation of markup and styling. Meaning both markup and styling may be inadvertently influenced by an outside source. Let's start with a basic directive and template:

angular.module('shadow.app', ['component.api'])
.directive('simpleDirective', function() {
    return {
      restrict: 'E',
      replace: false,
      templateUrl: 'template.html',
      transclude: true,
      scope: {
        dynamic: '='
      },
      link: function($scope, element) {
        // your code here
      }
    };
  })

Continue reading →

How to create (singleton) AngularJS services in 4 different ways

Posted on by  
Emil van Galen

Next to creating controllers and directives, AngularJS also supports “singleton” services. Services, like on the server-side, offer a great way for separating logic from your controllers. In AngularJS anything that’s either a primitive type, function or object can be a service. Although the concept of service is quite straight forward, the declaration of them in AngularJS isn’t:

  • There are 4 different ways to declare a service.
    • Registering a existing value as a service
    • Registering a factory function to create the singleton service instance
    • Registering a constructor function to create the singleton service instance
    • Registering a service factory which can be configured
  • Only 1 of them is extensively documented

Continue reading →

shadow-left