3

So I have a directive that Will be acting as a side panel in my app. When a user clicks a button the side panel will open. In said side panel I need the controller and view for this area to be dynamic based on which button the users clicks. I have found a way to load up the template dynamically but I am running into issues with loading the controller dynamically.

Enough talking here is the code.

Directive Code

app.directive('itemForm', function($compile) {
  var item1Template = '<div ng-include="view"></div>';
  var item2Template = '<h1> Hello item2 Form </h1>';
  var getTemplate = function(contentType) {
    if(contentType === 'item1') {
      return item1Template;
    } else if(contentType === 'item2') {
      return item2Template;
    }
  };
  return {
    restrict: 'E',
    replace: 'true',
    scope: {
      formType: '@formType'
    },
    //templateUrl: scope.template,
    link: function(scope, element) {
      if(scope.formType === 'item1') {
        scope.view = '/views/item1.html';
      }
      element.html(getTemplate(scope.formType)).show();
      $compile(element.contents())(scope);
    }
  };
});

Html

<item-form form-type='{{form.type}}'> </item-form>

Controller for view that directive lives in

$scope.form = {};
$scope.openItemOneDlg = function() {
    $scope.isFormOpen = !$scope.isFormOpen;  // this opens the side panel
    $scope.form.type = 'item1'; 
 };
$scope.openItemTwoDlg = function() {
    $scope.isFormOpen = !$scope.isFormOpen;  // this opens the side panel
    $scope.form.type = 'item2'; 
 };
Mindstormy
  • 490
  • 4
  • 14
  • Templates can be dynamically loaded outside the `link` function by using the `template` or `templateURL` property of the directive's object. Each can not only take a static value but also a function in the form `function(tElement, tAttrs) { ... }` – m.e.conroy Mar 06 '14 at 16:59
  • Yeah templates are not my issue I've got that working well, I'm having trouble assigning the controllers to use with each template. – Mindstormy Mar 06 '14 at 17:02
  • I had this problem back in November and posted here, I didn't get any good responses on how to do this and still haven't figured it out. – m.e.conroy Mar 06 '14 at 17:07
  • Does this answer give you what you need? I know it's tabbed but similar concept: http://stackoverflow.com/questions/21162467/angularjs-load-tabbed-content-directive-dynamicly – Jeremy Likness Mar 06 '14 at 17:57

1 Answers1

0

You can broadcast (using $broadcast) an event on click of the button. And have a listener (using $on) in the directive. This way, whenever the event is fired, directive logic will get executed.

You can refer the answer on this link for the usage of $broadcast and $on:

On-and-broadcast-in-AngularJS

Community
  • 1
  • 1
Adarsh Konchady
  • 2,577
  • 5
  • 30
  • 50