In HTML, I include an ID inside a directive:
<my-product data="id"></my-product>
In JavaScript:
angular.module('App', [])
.controller('Controller', ['$scope', function($scope) {
$scope.id = 'productDiv';
}])
.directive('myProduct', function() {
return {
restrict: 'E',
scope: {
data: '='
},
template: '<div id="{{data}}"></div>',
link: function(scope, element, attrs){
console.log(document.getElementById('productDiv'));
}
};
});
The data is shown in the template, but the console shows undefined because the template hasn't been loaded with data. How can I access the DOM after the data has been loaded? Thank you!
Using scope.$watch solves the problem:
In HTML:
<my-product prop="id"></my-product>
In JavaScript:
angular.module('App', [])
.controller('Controller', ['$scope', function($scope) {
$scope.id= 'productDiv';
}])
.directive('myProduct', function() {
return {
restrict: 'E',
scope: {
prop: '='
},
template: '<div id="{{prop}}"></div>',
link: function(scope, element, attrs){
scope.$watch('prop',function(){
console.log(document.getElementById(prop)); //get the DOM
});
}
};
});