AngularJS 指令运行时模板更改

AngularJS directive runtime template change

我一直在尝试制作一个输入指令,它允许不同的输入类型(例如间隔(最小-最大)、日期时间、数字、文本...)。每当用户更改数据类型时,相应的输入都会更改其模板,这一点非常重要。我还需要能够在页面上进行多个输入(请参阅 PLUNKR 以更好地理解)。

经过大量的反复试验和研究,我得出的结论是我需要观察属性(great-input),根据[=25=的值替换我输入的模板]ed 输入类型,并编译它。但是我无法在编译函数中执行此操作,而且我的手表在 link 函数中无法正常工作(我得到的是 t1,t2)。

所以,我需要做的是,在 select(type) 中更改值时,更改输入模板(为简单起见,我只是对不同的输入类型进行了颜色编码)。

$scope.$watch('greatInput', function (newVal) {
     console.log(newVal);
     html = getTemplate(newVal);
     $elem.html('').append($compile(html)($scope));
});

这几乎是应该完成工作的函数(根据它的实现位置进行了一些更改),但我找不到合适的位置。

完整代码: http://plnkr.co/edit/BCuiqg?p=preview

到目前为止,最简单的方法是在指令模板中使用 ng-ifs 并在范围上绑定输入类型:

.directive("greatInput", function(){
  return {
    template: '<input ng-if="isStr()" type="txt"    ng-model="greatInputModel">\
               <input ng-if="isInt()" type="number" ng-model="greatInputModel">\
               <input ng-if="isDbl()" type="number" ng-model="greatInputModel">',
    scope: {
      greatInputModel: "=",
      greatInputType: "@",
      // etc...
    },
    link: function($scope){
       $scope.isStr = function(){
          return $scope.greatInputType === "5" || someotherCondition();
       }
       // same for $scope.isInt and $scope.isDbl
    }
  }
});