单击角度 - 更新指令模板

时间:2014-03-21 22:34:43

标签: angularjs angularjs-directive

我正在尝试使用Angular构建页面。

我有两个模板,比如说

<script type='text/ng-template' id='a.html'>
    /*some html using {{data}} */
    <div><button>A</button></div>
</script>

<script type='text/ng-template' id='b.html'>
    /*some html using {{data}} */
    <div><button>B</button></div>
</script>

我想创建一个指令,当单击模板内的按钮时,它将模板从a更改为b,反之亦然。 我尝试了几个选项,查看类似问题的其他答案,但没有任何运气。 你能帮我找到最简单的方法吗?

2 个答案:

答案 0 :(得分:10)

ng-include是一个漂亮的指令,它接受范围变量作为参数。这样,您就可以动态加载(包括加载模板中的其他指令)。请参阅plnkr http://plnkr.co/edit/qxBVDWx6P0F0aNuOymct?p=preview

app.directive('dynamicTemplate', function(){
  return {
    restrict: 'A',
    replace: true,
    template: '<div><div ng-include="var"></div><div>current var: {{ var }}</div></div>',
    controller: function($scope){
      $scope.var = 'template1.html';
      $scope.change = function(where){
        $scope.var = where;
      }
    }
  };
});

但最好的方法是使用$stateProvider$routeProvider

处理

答案 1 :(得分:1)

这是一个不使用ng-include

的答案

http://jsfiddle.net/5DGkT/

它基本上从模板缓存中抓取它并编译它

if (newVal) {
    element.html($templateCache.get(newVal.type + '.html'));
    $compile(element.contents())(scope);
}
相关问题