angular - update directive template on click

旧城冷巷雨未停 提交于 2020-01-24 05:24:19

问题


I am trying to build a page using Angular.

I have two templates, say

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

and

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

I would like to create a directive that changes its template from a to b and vice versa when the button inside the template gets clicked. I tried several options, looking at other answers to similar questions, but without any luck. Can you help me to find the easiest way to do this?


回答1:


ng-include is a nifty directive that accepts a scope variable as the parameter. this way, you can dynamically load (including other directives from the loaded templates). See the 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;
      }
    }
  };
});

but the best way would be just deal with either using $stateProvider or $routeProvider




回答2:


Here's an answer that doesn't use ng-include

http://jsfiddle.net/5DGkT/

It basically grabs it from the template cache and compiles it

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


来源:https://stackoverflow.com/questions/22570717/angular-update-directive-template-on-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!