Метод углового 1,5-компонента templateUrl + function
Я пытаюсь получить приложение, работающее с угловым 1.5.0-бета-2.
Чтобы создать "директиву", у меня есть следующий код:
myApp.component('gridshow', {
bindings: {
slides: '='
},
controller: function() {
},
controllerAs: 'grid',
template: function ($element, $attrs) {
// access to $element and $attrs
return [
'<div class="slidegrid">',
'<div ng-repeat="slide in grid.slides">',
'{{slide.image}}',
'</div>',
'</div>'
].join('')
}
});
Мне нравится идея шаблона, который возвращает функцию с доступом к $element
и $attrs
но как я могу объединить это с templateUrl?
Ответы
Ответ 1
В 1.5.0-beta.2 templateUrl
может быть функцией, вызываемой инжектором. $element
и $attrs
вводятся как в template
и в функции templateUrl
в component
, а также любые другие зависимости.
Это значит, что
...
templateUrl: function ($element, $attrs) {
// access to $element and $attrs
...
return $attrs.uninterpolatedTemplateUrl;
}
может быть сделано вместо этого.
Ответ 2
Я решил эту проблему, следуя технике. Это может вам помочь.
шаблон
<div data-ng-repeat="field in $ctrl.fields track by $index">
<render-field data-field-type="{{field.type}}"></render-field>
</div>
Компонент
/**
* @ngdoc Component
* @name app.component.renderField
* @module app
*
* @description
* A component to render Field by type
*
* @author Mohan Singh ( gmail::[email protected], skype :: mohan.singh42 )
*/
(function () {
'use strict';
angular
.module('app')
.component('renderField', {
bindings: {
fieldType: '@',
},
template: '<div ng-include="$ctrl.templateUrl">',
controller: [
function () {
var $ctrl = this;
$ctrl.$onInit = initialization;
$ctrl.$onDestroy = onDestroy;
$ctrl.$onChanges = onChanges;
/**
* public properties
*/
/**
* public methods
*/
/**
* @function
* @name initialization
* @description
* A component lifeCycle hook which is called after all the controllers on an element have been constructed and had their bindings initialized
*/
function initialization() {
}
/**
* @function
* @name onChanges
* @description
* A component lifeCycle hook which is called when bindings are updated.
*/
function onChanges(bindings) {
if(bindings.fieldType && bindings.fieldType.isFirstChange()){
//$ctrl.fieldType['text' | 'textarea' | 'select' | 'radio']
$ctrl.templateUrl = 'partials/fields/'+$ctrl.fieldType+'.html';
}
}
/**
* @function
* @name onDestroy
* @description
* A component lifeCycle hook which is called when is called on a controller when its containing scope is destroyed.
* Usefull to release external resources, watches and event handlers.
*/
function onDestroy() { }
}]
});
})();
Ответ 3
Решение @estus работало для меня, пока я не очистил свои сценарии. Uglified он дал следующую ошибку:
Error: [$injector:unpr] Unknown provider: eProvider <- e
Решение, которое сработало для меня:
['$element', '$attrs', function($element, $attrs) {
return $attrs.uninterpolatedTemplateUrl;
}]