如何访问Angularjs的v1.5组件中的属性?

Chr*_*ris 10 web-component angularjs angularjs-directive

我正在使用v1.5组件,基本上(据我的理解扩展)最佳实践指令的包装器.

有关1.5版本组件的更多信息,请访问:http://toddmotto.com/exploring-the-angular-1-5-component-method/

我有以下内容:

<span>Correclty showing: {{ data.type }}</span>
<book class="details" type="data.type"></book>
Run Code Online (Sandbox Code Playgroud)

它的组件定义:

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
    }
});
Run Code Online (Sandbox Code Playgroud)

无论A)B)变化返回undefined.C)正确渲染.

有没有办法在返回模板字符串之前访问模板函数中的属性?

Jef*_*eff 13

在1.5中,templateUrl现在根据文档获取注射剂:https://docs.angularjs.org/guide/component.如果您使用ng-srict-di,除非您指定注射剂,否则您将收到错误....我正在使用ng-annotate来保存头痛并保持代码清洁.这是一个例子(在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
      }

  });
Run Code Online (Sandbox Code Playgroud)

或者在vanilla JS中没有ng-annotate:

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