AngularJS - 指令中的不同模板

Gio*_*nso 2 angularjs angularjs-directive angularjs-ng-repeat

我有一个基于twitter bootstrap的表单,每个字段都有自己的配置

// controller (the template shows this in ng-repeat

$scope.fields = [{name:"f1", label:"Field 1", with_button: false},
                 {name:"f2", label:"Field 2", with_button: true}]
Run Code Online (Sandbox Code Playgroud)

我正在尝试制作一个"条件指令",根据"field.with_button"自定义模板

// Without button
<div class="controls">
    <input type="text" id="i_{{field.name}}">
</div>

// With button
<div class="controls">
    <div class="input-append">
        <input type="text" id="i_{{field.name}}">
        <span class="add-on">bt</span>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我搜索了很多,没有找到任何解决方案,我试图只创建一个div并将内容放入编译器函数但它没有解析,如果我称之为$apply崩溃.

我怎么能做这个指令?

错了我上次尝试:

angular.module('mymodule',[]).directive('ssField', function() {
    return {
        transclude:false,
        scope: {
            field: '='
        },
        restrict: 'E',
        replace:true,
        template: '<div class="controls">{{innerContent}}</div>',
        controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs) {
            $scope.$eval('$scope.innerContent = \'<input type="text" id="input_{{field.name}}" placeholder="{{field.name}}" class="input-xlarge">\'');
        }]
    };
});

//<ss-field field="{{field}}"></ss-field>
Run Code Online (Sandbox Code Playgroud)

Cuo*_* Vo 5

您可以使用$http$compile服务来完成您所追求的目标.

http://plnkr.co/edit/Xt9khe?p=preview

这个plnkr应该说明需要做什么,但基本上:

  1. 用于$http根据条件加载模板.
  2. 使用加载模板与当前作用域编译$compile.
angular.module('mymodule',[]).directive('ssField', ['$http', '$compile', function($http, $compile) {
    return {
        transclude:false,
        scope: {
            field: '='
        },
        restrict: 'E',
        replace:true,
        template: '<div class="controls"></div>',
        link: function(scope, element, attrs) {
          var template;
          var withButtonTmpl = 'with_button.html';
          var withoutButtonTmpl = 'without_button.html';

          if (scope.field.with_button) {
            $http.get(withButtonTmpl).then(function(tmpl) {
              template = $compile(tmpl.data)(scope);
              element.append(template);
            });
          } else {
            $http.get(withoutButtonTmpl).then(function(tmpl) {
              template = $compile(tmpl.data)(scope);
              element.append(template);
            });
          }
        }
    };
}]);
Run Code Online (Sandbox Code Playgroud)

您可以将指令更改为更健壮,因此URL不会直接嵌入指令中以便重新使用等,但概念应该类似.