Achuth hadnoor Achuth hadnoor - 1 month ago 10
AngularJS Question

how to create custom directives in Angularjs that changes its state of being used in application using an id?

I am working on an application that has same directives but the content change and template depends on the id of a controller in a module.

app.directive('glTranslate', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var key = element.text();
attrs.$observe('options', function(value) {
var options;

try {
options= JSON.parse(value);
element.text( I18n.t( key, options ) );
} catch (err) {
// SyntaxError maybe thrown as the options string is dynamically updated through Angular bindings
// and the options string may be momentarily be syntactically incorrect
console.log("Error parsing options: " + value + "\nError:"+ err.message + "\n");
}
});
}
};
});

Answer

If I understand you correctly, to set a directive's template dynamically based on some condition, you can use ng-include inside the directive. The pseudocode below works. It includes an example directive with dynamic template chosen based attribute passed to it and simple HTML usage. Needless to say, although the template contents vary, here they use the same directive controller and its accompanying functionality. Hope this helps.

.directive("dynaDirective", function() {
  return {
    template: '<ng-include src="getTemplateUrl()"/>',
    scope: {
        someData: '='
    },
    restrict: 'E',
    controller: function($scope) {
      //function used on the ng-include to resolve the template
      $scope.getTemplateUrl = function() {
        //basic handling

        return "templateName" + $scope.someData.type;

      }

      $scope.doSomething1 = {
        //......
      }
      
      $scope.doSomething2 = {
        //......
      }      
    }
  };
});
<dyna-directive some-data="someObject"></dyna-directive>