Chris
Chris

Reputation: 58182

How to access attributes within Angularjs's v1.5 component?

I am using the v1.5 component, which is essentially (as far as my understanding extends) a wrapper for best practice directives.

More info about the 1.5 release of component can be found here: http://toddmotto.com/exploring-the-angular-1-5-component-method/

I have the following:

<span>Correclty showing: {{ data.type }}</span>
<book class="details" type="data.type"></book>

And it's component definition:

angular
.module('app')
.component('book', {
    bindings: {
        type: '='
    },
    template: function($element, $attrs) {
        // Have tried A):
        // console.log($attrs.type); // <- undefined

        // And B):
        $attrs.$observe('type', function(value) {
            console.log(value); // <- undefined
        });

        // But.. C):
        return "This works though {{ book.type }}"; // <- renders
    }
});

Both A) and B) variations return undefined. C) renders correctly.

Is there a way to access attributes within the template function before returning the template string?

Upvotes: 10

Views: 9974

Answers (1)

Jeff
Jeff

Reputation: 846

In 1.5, templateUrl now takes injectables according to the docs: https://docs.angularjs.org/guide/component. If you use ng-srict-di you will get an error unless you specify the injectables....I'm using ng-annotate to save the headaches and keep the code clean. Here's an example (in TypeScript):

  import IRootElementService = angular.IRootElementService;
  import IAttributes = angular.IAttributes;

  angular.module('app').component('book', {

      /*@ngInject*/
      templateUrl($element:IRootElementService, $attrs:IAttributes) {
           // access to the $element or $attrs injectables
      }

  });

or without ng-annotate in vanilla JS:

  angular.module('app').component('book', {    
      templateUrl: ['$element', '$attrs', function($element, $attrs) {
           // access to the $element or $attrs injectables
      }],
  });

Upvotes: 13

Related Questions