我想通过绑定(bind)将自定义模板传递到 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>
有什么办法吗?
最佳答案
如果您想要动态模板,您可以利用可以将函数传递给组件 template
的事实,在函数可注入(inject)的组件中,我建议您引用 this问题以获取更多信息,但主要思想如下:
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();
}
});
关于javascript - 如何通过绑定(bind)将模板传递给 AngularJS 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46349067/