R
R
Roman2014-10-23 13:34:39
JavaScript
Roman, 2014-10-23 13:34:39

How to dynamically create a directive in an AngularJS controller?

Hello!
There is the following task:
In an AngularJS SPA, in a specific controller, you need to dynamically declare a directive received from the server using AJAX.
On the server, I have directives that describe input forms (more than 3000 forms).
More precisely, I declare the directive once, but I want to set its implementation dynamically based on the received data.
Tried the following:

// метод контроллера
$scope.add = function(ev,attrs){
        //ajax вызов
        .success(function (data, status, headers, config) {
        // получили директиву с сервера
        var exFormDirective = data.newForm;
       // добавили ее к модулю
        myApp.directive('exForm', exFormDirective );
       // динамически создали элемент
       var exFunction = angular.element(document.createElement('ex-Form'));
       // скомпилировали 
       var el = $compile( exFunction )( $scope );
       // Добавили созданный элемент на страницу
        angular.element(document.getElementById('exTempleate')).append(exFunction);

I don’t get any errors when executing, but the directive is not dynamically created either ((
If you do the same with a previously described and connected directive (that is, connect not in the controller, but standardly) - then everything works.
But since there are a lot of directives - then arranging everything in advance seems an impossible task
.
// добавили ее к модулю
        myApp.directive('exForm', exFormDirective );

But what exactly is wrong, can someone tell me?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Sydorenko, 2014-10-23
@San40

Here is something about your problem
stackoverflow.com/questions/15279244/dynamically-a...
jsfiddle.net/ftfish/KyEr3
But the essence is the same, the directive must be included .. It is possible not to participate in the current html output, but to be described from the code received via Ajax, but the directive code itself (controllers, linkers, etc.) must be present.
Otherwise.. something like this weblogs.thinktecture.com/pawel/2014/07/angularjs-d...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question