惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Vercel News
Vercel News
O
OpenAI News
Engineering at Meta
Engineering at Meta
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
月光博客
月光博客
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
WordPress大学
WordPress大学
宝玉的分享
宝玉的分享
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
云风的 BLOG
云风的 BLOG
罗磊的独立博客
S
SegmentFault 最新的问题
The Register - Security
The Register - Security
Hugging Face - Blog
Hugging Face - Blog
D
DataBreaches.Net
U
Unit 42
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
B
Blog
阮一峰的网络日志
阮一峰的网络日志
P
Proofpoint News Feed
雷峰网
雷峰网
V
Visual Studio Blog
小众软件
小众软件
aimingoo的专栏
aimingoo的专栏
N
Netflix TechBlog - Medium
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Y
Y Combinator Blog
博客园 - 【当耐特】
G
Google Developers Blog
L
LangChain Blog
Stack Overflow Blog
Stack Overflow Blog
I
InfoQ
Martin Fowler
Martin Fowler
F
Fortinet All Blogs
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
The Cloudflare Blog
AI
AI
Google Online Security Blog
Google Online Security Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
博客园 - Franky
Blog — PlanetScale
Blog — PlanetScale
Webroot Blog
Webroot Blog
PCI Perspectives
PCI Perspectives
爱范儿
爱范儿
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org

Minko Gechev's blog

skillgrade Unit Tests for AI Agent Skills You Should Care About AI Generative Development LLM-first Web Framework Reactive framework in ~200 lines of JavaScript Managing Angular Are LLMs going to replace us? Prefetching Heuristics Design Patterns in Open Source Projects - Part II Design Patterns in Open Source Projects - Part I What I learned doing 125 public talks - Part I Dynamic imports solve all the problems, right? 5 Angular CLI Features You Didn't Know About Angular quicklink Preloading Strategy Introducing Bazel Schematics for Angular CLI Building TypeScript Projects with Bazel Joining Google Playing Mortal Kombat with TensorFlow.js. Transfer learning and data augmentation Fast, extensible, configurable, and beautiful linter for Go Introducing Guess.js - a toolkit for enabling data-driven user-experiences on the Web Machine Learning-Driven Bundling. The Future of JavaScript Tooling. JavaScript Decorators for Declarative and Readable Code 3 Tricks For Using Redux and Immutable.js with TypeScript Follow Your Dream Career with Open Source. Personal Story. Redux Anti-Patterns - Part 1. State Management. Faster Angular Applications - Understanding Differs. Developing a Custom IterableDiffer Faster Angular Applications - Part 2. Pure Pipes, Pure Functions and Memoization Faster Angular Applications - Part 1. On Push Change Detection and Immutability Understanding Dynamic Scoping and TemplateRef Implementing a Simple Compiler on 25 Lines of JavaScript Developing Statically Typed Programming Language WebVR for a Gamified IDE 7 Angular Tools That You Should Consider Announcing ngrev - Reverse Engineering Tool for Angular Implementing Angular's Dependency Injection in React. Understanding Element Injectors. Distributing an Angular Library - The Brief Guide Angular in Production Ahead-of-Time Compilation in Angular 2.5X Smaller Angular 2 Applications with Google Closure Compiler Using Stripe with Angular (Deprecated) Building an Angular Application for Production Implementing the Missing "resolve" Feature of the Angular 2 Router Scalable Single-Page Application Architecture Managing ambient type definitions and dealing with the "Duplicate identifier" TypeScript error Static Code Analysis of Angular 2 and TypeScript Projects Enforcing Best Practices with Static Code Analysis of Angular 2 Projects ViewChildren and ContentChildren in Angular Dynamically Configuring the Angular's Router Angular 2 Hot Loader Lazy Loading of Route Components in Angular 2 Aspect-Oriented Programming in JavaScript Flux in Depth. Store and Network Communication. Using JSX with TypeScript Flux in Depth. Overview and Components. Even Faster AngularJS Data Structures Boost the Performance of an AngularJS Application Using Immutable Data - Part 2 Angular2 - First Impressions Build Your own Simplified AngularJS in 200 Lines of JavaScript Persistent State of ReactJS Component Boost the Performance of an AngularJS Application Using Immutable Data Processing Binary Protocols with Client-Side JavaScript Stream your Desktop to HTML5 Video Element Multi-User Video Conference with WebRTC Asynchronous calls with ES6 generators Binary Tree iterator with ES6 generators WebRTC chat with React.js AngularJS in Patterns (Part 3) AngularJS in Patterns (Part 2). Services. Using GitHub Pages with Jekyll! AngularJS in Patterns (Part 1). Overview of AngularJS Singleton in JavaScript Express over HTTPS What I get from the JavaScript MV* frameworks Remote Desktop Client with AngularJS and Yeoman The magic of $resource (or simply a client-side Active Record) AngularAOP v0.1.0 Advanced JavaScript at Sofia University AngularJS style guide Lazy prefetching of AngularJS partials VNC client on 200 lines of JavaScript Aspect-Oriented Programming with AngularJS CSS3 flipping effect Practical programming with JavaScript Why I should use publish/subscribe in JavaScript JavaScript, the weird parts Functional programming with JavaScript plainvm Looking for performance? Probably you should NOT use [].sort (V8) JavaScript image scaling ELang Caching CSS with localStorage Self-invoking functions in JavaScript (or Immediately Invoked Function Expressions) Asus N56VZ + Ubuntu 12.04 (en) Asus N56VZ + Ubuntu 12.04 Debian Squeeze + LXDE on Google Nexus S (or having some fun while suffering) HTML5 image editor Курсови проекти – ФМИ Carousel Gallery SofiaJS...
AngularJS Inheritance Patterns
2013-12-18 · via Minko Gechev's blog

Since AngularJS does not provide any built-in features for using inheritance, in this blog post I’ll describe how the general JavaScript inheritance patterns can be applied to AngularJS components.

Controllers inheritance

First, lets talk about controllers. Actually it is very unlikely to inherit from parent controller (except when you’re using the controller as syntax, see below). This is the case because by implementation the scope in the child controller will inherit prototypically from its parent scope. So when you need to reuse functionality from the parent controller, all you need to do is add the required methods to the parent scope. By doing this the child controller will have access to all these methods through the prototype of its scope i.e.:

myModule.controller('ParentCtrl', function ($scope) {
  $scope.parentMethod = function () {
    //body...
  };
});

myModule.controller('ChildCtrl', function ($scope) {
  $scope.parentMethod(); //it'll work
});

Of course, the inheritance creates very strong coupling but only in a single direction (i.e. the child is strongly coupled to its parent), so you can’t directly call children methods from your parent controller. For doing this you need to use event dispatching:

myModule.controller('ParentCtrl', function ($scope) {
  $scope.$broadcast('event', args);
  $scope.$on('event-response', function (result) {
  });
});

myModule.controller('ChildCtrl', function ($scope) {
  $scope.$on('event', function (args) {
    var result;
    //body...
    $scope.$emit('event-response', result);
  });
});

I’m providing this snippet with only informative purpose, if you need to call children methods from your parent controller, you might be doing something wrong.

OK, but now let’s imagine you have two pages with almost the same functionality, lets say the intersection between the functionality of the pages is more than 50%. They might have totally different views but the logic behind these views could be quite similar. In such case you can create a base controller which encapsulates the common logic, and two children controllers which inherit from it. The base controller is not necessary to be implemented as AngularJS controller component you can use simple constructor function:

function BaseCtrl($scope, $location, ...) {
  $scope.commonScopeMethod = function () {
    //body
  };
  $scope.commonVar = 42;
}
BaseCtrl.prototype.commonMethod1 = function () {
  //body
};
BaseCtrl.prototype.commonMethod2 = function () {
  //body
};

Now the children controllers can easily inherit from the base controller by:

function ChildCtrl1($scope, $location, ...) {
  BaseCtrl.call(this, $scope, $location, ...);
  $scope.childScopeMethod = function () {
    this.commonMethod2();
  };
}

ChildCtrl1.prototype = Object.create(BaseCtrl.prototype);

ChildCtrl1.prototype.childMethod1 = function () {
  this.commonMethod1();
};

//Register ChildCtrl1 as AngularJS controller
myModule.controller('ChildCtrl1', ChildCtrl1);

As you can see we directly apply the “Klassical” inheritance pattern. We can do the same for the second child controller. You can check example right here.

Controller as syntax

AngularJS 1.2 added the controller as syntax. Basically it allows us to create aliases for our controllers, for example using the ng-controller directive we can:

<div ng-controller="MainCtrl as main">
  {{ main.name }}
  <button ng-click="main.clicked()">Click</button>
</div>

with the following controller:

function MainCtrl() {
  this.name = 'Foobar';
}
MainCtrl.prototype.clicked = function () {
  alert('You clicked me!');
};

There are number of benefits, which come along with this syntax one of them is the way we can take advantage of the “klassical” JavaScript inheritance:

function BaseCtrl() {
  this.name = 'foobar';
}
BaseCtrl.prototype.parentMethod = function () {
  //body
};

function ChildCtrl() {
  BaseCtrl.call(this);
  this.name = 'baz';
}
ChildCtrl.prototype = Object.create(BaseCtrl.prototype);
ChildCtrl.prototype.childMethod = function () {
  this.parentMethod();
  //body
};

app.controller('BaseCtrl', BaseCtrl);
app.controller('ChildCtrl', ChildCtrl);

which can be used with the following markup:

<div ng-controller="BaseCtrl as base">
  <button ng-click="base.method()">Invoke parent</button>
  <div ng-controller="ChildCtrl as child">
    <button ng-click="child.childMethod()">Invoke child</button>
  </div>
</div>

When the user press the button with label “Invoke parent” the parentMethod defined in BaseCtrl will be invoked. If the user press “Invoke child” the childMethod will be invoked. Notice that in its body it invokes parentMethod as well.

Services inheritance

As you know there are two ways to create injectable (through DI) AngularJS services:

  • module.factory(name, factoryFn)
  • module.service(name, factoryFn)

module.factory

In module.factory the factoryFn returns object literal which is the actual service. Behind the scene AngularJS calls the factory function inside the injector definition

If you need inheritance in services which are instantiated through module.factory the prototype inheritance pattern through Object.create fits just great!

Lets create the base service:

var BaseService = (function () {
  var privateVar = 0;
  return {
    someAwesomeStuff: function () {
      if (privateVar === 42) {
        alert('You reached the answer!');
      }
      privateVar += 1;
    };
  };
}());

and here is the child service:

var ChildService = Object.create(BaseService);
ChildService.someMoreAwesomeStuff = function () {
  //body...
};

module.factory('ChildService', function () {
  return ChildService;
});

Now you can inject ChildService in different component and reuse the inherited from BaseService functionality.

function MyCtrl(ChildService) {
  ChildService.someAwesomeStuff();
}

You can find an example right here.

Inject the parent

One more pattern for inheritance with services is injecting the parent through dependency injection and creating new object, which inherits from the parent prototypically:

module.factory('ParentService', function ($q, $http) {
  return {
    //public API
  };
});

module.factory('ChildService', function (ParentService, $sce) {
  var child = Object.create(ParentService);
  child.childMethod = function () {
    //extending the parent
  };
  return child;
});

This pattern is definitely much more useful when you need to inject some dependencies to the parent service before inheriting it.

module.service

Usually I call the variables attached to my scope View Models and the special services, which encapsulate the business logic – Models. I implement these services with something close to the Active Record Pattern. My models are usually responsible for talking to the server, sometimes directly but usually through a Gateway. For the creation of these models I prefer to use module.service method. Internally these services are created through the instantiate method.

Why I prefer using service instead of factory? Well, may be I’m a confused developer who doesn’t understand the true power of the prototypal inheritance used with object literals, however I prefer to use the classical one for my models. By using it I can create a set of constructor functions which model my domain pretty well. One day I may decide to use MDD and generate all my models from some fancy UML diagrams…

Here is an example of how you can take advantage of the Klassical inheritance pattern for AngularJS services created with module.service:

function Human(name) {
  this.name = name;
}
Human.prototype.talk = function () {
  return 'My name is ' + this.name;
};
Human.$inject = ['name'];

function Superhero(name, abilities) {
  Human.call(this, name);
  this.abilities = abilities;
}
Superhero.prototype = Object.create(Human.prototype);
Superhero.prototype.saveTheWorld = function () {
  return 'Saving the world with ' + this.abilities.join(', ');
};
Superhero.$inject = ['name', 'AbilitiesCollection'];

angular.module('demo').service('Human', Human);
angular.module('demo').service('Superhero', Superhero);
angular.module('demo').value('name', 'Super Dev');
angular.module('demo').value('AbilitiesCollection', ['C++', 'JavaScript']);

Here is a talk on this topic I gave on Angular Berlin: