我试图写一个非常灵活的指令。为了做到这一点,我希望用户定义一个在我的返回部分使用的模板(如
ui-bootstrap typeahead directive所示)。
所以我定义我的模板像这样:
<script type="text/ng-template" id="myDirectivesCustomTemplate.html"> <ul> <li ng-repeat="value in values"> <a ng-click="doSomething(value.id)"> {{value.name}} </a> </li> </ul> </script>
我将此模板设置为我的指令
<div my-directive my-directive-custom-template="myDirectivesCustomTemplate.html" my-directive-data="someScopeData">
现在在我的指令中,我如何渲染自定义模板并使用传递的数据?当我尝试使用它直接返回模板时会抛出一个ReferenceError:$ scope未定义Error。如果我没有范围调用它,它会引用ReferenceError:myDirectiveCustomTemplate未定义错误。
如果我不想直接使用它作为回报,我可以在哪里和如何使用我的模板?
编辑:让我们说,这是我的指示:
(function() { 'use strict'; var ComboBox = function() { var displayInputField = elem.find('input.dropdown'); scope.$watch(scope.nsdComboBoxModel,function(newVal){ /* search for newVal in given data object */ scope.setDisplayInputValue(newVal); }); scope.setDisplayInputValue = function(value) { displayInputField.val(value); }; scope.elementSelected = function (item,model,label) { scope.ComboBoxCallback(item); scope.setDisplayInputValue(label); }; } return { restrict: 'A',transclude: true,scope: { ComboBox: '@',/* used as HTML/css-id/name/path */ ComboBoxModel: '=',/* the actual AngularJS model (ng-model) */ ComboBoxAutocompleteData: '=',/* the data used for autoComplete (must be array of objects having id and value) */ ComboBoxDropdownData: '=',/* data used by the dropdown template */ ComboBoxCallback: '=',/* a callback function called with selected autocomplete data item on select */ ComboBoxLabel: '@',/* label for the input field */ ComboBoxDropdownTemplate: '@' /* label for the input field */ },template: '<section class="-comboBox-directive container-fluid">' + '<label for="{{ComboBox}}" ng-if="ComboBoxTranslation" translate="{{ComboBoxLabel}}"></label>' + '<div class="comboBox input-group">' + '<input type="text" ' + 'id="{{ComboBox}}" ' + 'autocomplete="off" ' + 'ng-model="ComboBoxDestinationDisplay" ' + 'data-toggle="dropdown" ' + 'typeahead="value as location.value for location in ComboBoxAutocompleteData | filter:$viewValue" ' + 'typeahead-editable="false" ' + 'typeahead-on-select="elementSelected($item,$model,$label)" ' + 'class="form-control dropdown">' + // dropdown-toggle '<span data-toggle="dropdown" class="input-group-addon dropdown-toggle">' + '<span class="glyphicon glyphicon-globe"></span>' + '</span>' + //$compile(ComboBoxDropdownTemplate) + '</div>' + '</section>',link: link }; }; angular.module('vibe.directives').directive('nsdComboBox',[NsdComboBox]); })();