簡體   English   中英

如何通過綁定到AngularJS組件傳遞模板

[英]How to pass a template via bindings to an AngularJS Component

我想通過綁定將自定義模板傳遞到AngularJS組件,並使用其作用域進行渲染。 像這樣的東西(偽代碼,這不起作用):

angular
  .module('myApp', [])
  .controller('mainController', ($scope) => {

    $scope.getTemplate = () => (`
      <div>
        <span>{{$ctrl.name}}</span>
      </div>
    `)
  })
  .component('myComponent', {
    controller: ($scope, $compile) => {
      const $ctrl = $scope.$ctrl;

      $ctrl.$onInit = () => {
        $ctrl.name = 'Hello World!';
      };

      $ctrl.compileTemplate = () => $compile($ctrl.template())($scope);
    },
    bindings: {
      template: '&'
    },
    template: `
      <div>
        My dynamic content: {{$ctrl.compileTemplate()}}
      </div>
  `
  });

用法:

<div ng-controller="mainController as $ctrl">
  <my-component template="$ctrl.getTemplate()"></my-component>
</div>

預期結果:

<div>
  My custom content:
  <div>
    <span>Hello World!</span>
  </div>
</div>

有什么辦法嗎?

您可以使用$compile服務創建一個指令來處理所涉及的DOM操作。

以下工作片段實現了一個attribute指令compile ,該指令在控制器范圍內compile該屬性的輸入值。 它基本上是將您的模板添加到該指令所附加的元素的內部內容中,並最終對其進行編譯。

 angular.module('app', []) .run(($rootScope) => { $rootScope.name = 'world'; $rootScope.template = ` <label>Name</label> <input type="text" ng-model="name"> <h2>Hello {{ name }}!</h2> `; }) .directive('compile', ($compile) => { return (scope, element, attrs) => { scope.$watch( scope => scope.$eval(attrs.compile), value => { element.html(value); $compile(element.contents())(scope); } ); }; }) 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.js"></script> <div ng-app="app"> <div compile="template"></div> </div> 

如果你想動態模板,你可以利用的事實,你可以傳遞給組件的功能template ,在功能部件注射,我是指你這個問題更多的信息,但這里是主要的想法:

angular
  .module('myApp', [])
  .factory('tempalteFactory', {
      return getTemplate() {
          retrun '<b> yep </b>';
      }
  })
  .component('myComponent', {
    controller: ($scope, $compile) => {
      const $ctrl = $scope.$ctrl;

      $ctrl.$onInit = () => {
        $ctrl.name = 'Hello World!';
      };   

    },
    template: function($element, $attrs, templateFactory) {
          'ngInject';

          return templateFactory();
    }    
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM