首页 > 解决方案 > 如何将对象传递给angularjs中组件的模板函数

问题描述

我有一个 angularjs 1.7.x 项目,我使用一个组件在网站页面中添加图像和链接,如下所示:

angular.module('app', [])
.controller('MainCtrl', function MainCtrl() {
  this.book = {
    id: 12,
    name: 'Spawn'
  };
})
.component('smallBook', {
  bindings: {
    book: '<'
  },
  template: function($element, $attrs) {
      // here where is I need to use passed book object ...
      console.log("this.book", this.book); // book is undefined !???
      return '<span>Name: {{$ctrl.book.name}}</span>';
    }
});

并像这样在视图中使用该组件:

<div ng-controller="MainCtrl as ctrl">
   <b>Book</b>
   <br>
   <small-book book="ctrl.book"></small-book>
</div>

您可以在plunker中看到此示例代码

现在我需要访问组件模板中使用的传递对象,但我希望在模板编译时间之前获得它。我$attrs在模板函数中使用过,但它会将对象的值作为字符串!帮助我解决这个问题或使用其他方式在编译时间之前并根据传递的对象注入我的模板。

标签: angularjstemplatesdata-bindingangularjs-componentsinjectable

解决方案


推荐阅读