Sam
Sam

Reputation: 15771

AngularJS Controller as syntax and Directives

So I have been exploring the Controller as syntax in AngularJS, and I want to know how to deal with directives and $scope, specifically inheritance of the controllers $scope or properties from a child directive.

I am using Typescript, so given this controller:

export class DefaultController implements IDefaultController {
    customer: Models.ICustomer;

    static $inject = ['$scope', 'config', 'customerDataService'];

    constructor(private $scope: ng.IScope, private config: ApplicationConfig, private customerDataService: Services.ICustomerDataService) {

    }

    getCustomerById(id: number): void {
        console.log(this.config.version);
        this.customerDataService.getCustomer(id).then((customer) => {
            this.customer = angular.extend(new Models.Customer(), customer);

        });
    }
}

How would I go about passing the customer down to a directive which would typically inherit the $scope of the parent controller.

Upvotes: 1

Views: 680

Answers (1)

Radim Köhler
Radim Köhler

Reputation: 123861

In case we would declare as like this (inside of a View):

<div ng-controller="DefaultController as Events">
 ...

Almost the same for Directive def:

export class MyDefaultDirective implements ng.IDirective
{
    public restrict: string = "E";
    public replace: boolean = true;
    ...
    public controller: string = "DefaultController as Events";
    ...

We can expect, that the instance of this controller will be injected into $scope like this:

// this was done by angular
// - the 'as' part was used for a property name
// - current controller instance was injected 
var controller = this.$scope.Events;

So we can now access any public stuff of our controller. A bit simplified (but exact) version of the above controller snippet:

export class DefaultController implements IDefaultController {
    // explicit public just to show that this will be available
    public customer: Models.ICustomer;
    ....

    getCustomerById(id: number): void {
        this.customerDataService.getCustomer(id).then((customer) => {

            // HERE
            // this.$scope.Events.customer is ready for use
            this.customer = angular.extend(new Models.Customer(), customer);
      ...

In our View (once loaded via $http) we can consume above result like this:

<div>
  {{Events.customer}} // public propeties of this.$scope

Upvotes: 1

Related Questions