如何在AngularJS指令中使用定义的text / ng-template

时间:2014-03-31 09:05:26

标签: angularjs templates angularjs-directive

我尝试编写一个非常灵活的指令。为此,我希望用户定义一部分返回时使用的模板(如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 is not defined错误。如果我在没有范围的情况下调用它,则会显示ReferenceError: myDirectiveCustomTemplate is not defined错误。

如果我不想直接使用我的模板,我可以在哪里以及如何使用我的模板?

编辑:让我们说,这是我的指示:

(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]);
})();

4 个答案:

答案 0 :(得分:15)

HTML

<script type="text/ng-template" id="myDirectivesCustomTemplate.html">
    <ul>
        <li ng-repeat="value in values">
        <a ng-click="doSomething({id:value.id})">
                            {{value.name}}
        </a>
        </li>
    </ul>
</script>
<div ng-controller="MainCtrl">
     <div my-directive template="myDirectivesCustomTemplate.html" mydata="mydata" mycallback="doSomething(id)"></div>
</div>

JS

app.controller('MainCtrl',function($scope){
    $scope.mydata = [{id:1,name:'One'},{id:2,name:'Two'},{id:3,name:'Three'}];
    $scope.doSomething = function(id){
        alert(id); 
    }
});
app.directive('myDirective', function($templateCache,$compile) {
    return {
        restrict: 'A',
        scope:{
            template : "@",
            mydata : "=",
            mycallback:"&"
        },
        link: function(scope,element) {
            var template = $templateCache.get(scope.template);
            scope.values = scope.mydata;
            scope.doSomething = scope.mycallback;
            element.append($compile(template)(scope));
        }
    }
});

答案 1 :(得分:13)

查看您的指示我可以建议尝试ng-include。你想去哪里

//$compile(ComboboxDropdownTemplate) +

    '</div>'

将其更改为

<span ng-include='templateUrlPropertyOnScope'>

'</div>'

templateUrlPropertyOnScope属性应指向服务器端或使用type=text/ng-template创建的脚本部分中的模板。

答案 2 :(得分:3)

您可以使用$http$compile来完成此任务。

app.directive('myDirective', function($http, $templateCache, $compile) {
  return {
    scope: {
      // reference to your data. 
      // Just use `data.values` or `data.whatever` in your template
      data: '=myDirectiveData'
    },
    link: function(scope, elm, attrs) {
      // Load the template via my-directive-custom-template attribute
      $http.get(attrs.myDirectiveCustomTemplate, {cache: $templateCache}).success(function(html) {
        // update the HTML
        elm.html(html);
        // compile the html against the scope
        return $compile(elm.contents())(scope);
      });
    }
  };
});

我希望它能给你一个良好的开端

答案 3 :(得分:3)

我知道这是4年后的事情,但是如果有人仍然有这个问题,也许这个答案也可能有用。

使用这样的简单指令:

<my-directive template="custom-template.html"></my-directive>

然后您可以在指令中引用模板属性,如下所示:

(function() {
  angular
    .module('app')
    .directive('myDirective', myDirective);

  function myDirective() {
    return {
      restrict: 'E',
      templateUrl: function(elem, attrs) {
        return attrs.template;
      }
    }
  }
}