J
J
Jiakki-js2014-08-30 16:08:52
JavaScript
Jiakki-js, 2014-08-30 16:08:52

How to access a dynamically created element in angular?

How to get an element with a directive that was created dynamically?

<div test ></div> // динамически создан


App.directive("test", function(){

........
 element. ....... // так не работает


})

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2014-08-30
@Jiakki-js

Uh ... turn on the telepath mode.
Let's say you have the following code:

angular.module('app', [])

.directive('foo', function () {
    return function (scope, el, attr) {
        el.append('<div bar></div>');
    }
}
.directive('bar', function () {
    return function (scope, el, attr) {
        console.log('init bar directive');
    }  
});

there is a pattern
<div ng-app="app">
    <div foo></div>
</div>

And when the application is launched, we do not see our log console in the console and get upset.
And why? but because angular does not track the appearance / removal of new elements by itself, and does not try to look for directives for every sneeze. To do this, he must be asked to collect the directive.
angular.directive('foo', function ($compile) {
    return function (scope, el, attr) {
        var child = $compile('<div bar></div>')(scope);
        el.append(child);
    }
});

If you need to do this when initializing the directive, it’s easier to put the directives in the template and then angular will do everything itself, since it will do $ compile inside anyway.
Read more here: https://docs.angularjs.org/api/ng/service/$compile

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question