Search code examples
angularjsangularjs-components

AngularJS: Use variable inside component


I want to use an input variable and display it inside my component HTML but I can't get it to work.

I'm pretty sure I miss something important here but can't say what.

Here is my component declaration:

app.component('requestSummary', {
    templateUrl: "./Template/request-summary",
    controller: function RequestSummary() {
        var vm = this;
    },
    bindings: {
        request: "="
    }
});

The component template:

<div>
    <h1>{{ vm.request.Pnr }}</h1>
</div>

(I have also tried without the vm)

The component use:

<md-card ng-repeat="request in vm.requests">
    <md-card-content>
        <request-summary request="request"></request-summary>
    </md-card-content>
</md-card>

When I do a console.log(vm) inside the component controller, I can see my request is there:

enter image description here

But I don't know how to print it inside the HTML.

Any help is appreciated.


Solution

  • Components have an automatic default controllerAs controller with an alias of $ctrl. You need to use:

    <div>
        <h1>{{ $ctrl.request.Pnr }}</h1>
    </div>
    

    And you can get rid of the var vm = this;.