Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 1.5 component method templateUrl + function

Tags:

I'm trying to get an app working with angular 1.5.0-beta.2

To make a 'directive' I have the following code:

myApp.component('gridshow', {
  bindings: {
    slides: '='
  },
  controller: function() {

  },
  controllerAs: 'grid',
  template: function ($element, $attrs) {
    // access to $element and $attrs
    return [
      '<div class="slidegrid">',
      '<div ng-repeat="slide in grid.slides">',
      '{{slide.image}}',
      '</div>',
      '</div>'
    ].join('')
  }
});

I like the idea of the template that returns a function with access to $element and $attrs but how do I combine this with a templateUrl?

like image 400
tuvokki Avatar asked Nov 21 '15 09:11

tuvokki


People also ask

What is templateUrl in angular?

When to use templateUrl in Angular applications? When you have a complex view, then it recommended by Angular to create that complex view in an external HTML file instead of an inline template. The Angular component decorator provides a property called templateUrl. This property takes the path of an external HTML file.

What is @component in angular?

Components are the most basic UI building block of an Angular app. An Angular app contains a tree of Angular components. Angular components are a subset of directives, always associated with a template. Unlike other directives, only one component can be instantiated for a given element in a template.

What is Oninit in AngularJS?

A callback method that is invoked immediately after the default change detector has checked the directive's data-bound properties for the first time, and before any of the view or content children have been checked. It is invoked only once when the directive is instantiated.

What is $Ctrl in AngularJS?

$ctrl is the view model object in your controller. This $ctrl is a name you choose (vm is another most common name), if you check your code you can see the definition as $ctrl = this; , so basically its the this keyword of the controller function.


2 Answers

In 1.5.0-beta.2 templateUrl can be a function that is invoked by injector. $element and $attrs are injected into both template and templateUrl functions in component, as well as any other dependencies.

This means that

  ...
  templateUrl: function ($element, $attrs) {
    // access to $element and $attrs
    ...
    return $attrs.uninterpolatedTemplateUrl;
  }

can be done instead.

like image 111
Estus Flask Avatar answered Sep 17 '22 18:09

Estus Flask


@estus solution worked for me until I uglified my scripts. Uglified it gave the following error:

Error: [$injector:unpr] Unknown provider: eProvider <- e

The solution that worked for me is:

['$element', '$attrs', function($element, $attrs) {
    return $attrs.uninterpolatedTemplateUrl;
}]
like image 32
Backer Avatar answered Sep 18 '22 18:09

Backer