Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular - update directive template on click

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?

like image 506
marcosh Avatar asked Mar 21 '14 22:03

marcosh


Video Answer


1 Answers

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

like image 62
pocesar Avatar answered Sep 21 '22 19:09

pocesar