1

in html,i bind id inside directive:

<my-customer data="id"></my-customer>

in js:

angular.module('Main', [])
.controller('Controller', ['$scope', function($scope) {
    $scope.id= 'divId';
}])
.directive('myCustomer', function() {
    return {
        restrict: 'E',
        scope: {
            data: '='
        },
        template: '<div id="{{data}}"></div>',
        link: function(scope,element,attrs){
            console.log(document.getElementById('divId'));
        }
    };
});

It can show data in template,but console shows undefined because the template hasn't been loaded with data,how i get the dom after data has been loaded? Thank you!


Using scope.$watch solve the problem:

in html:

<my-customer param="id"></my-customer>

in js:

angular.module('Main', [])
.controller('Controller', ['$scope', function($scope) {
    $scope.id= 'divId';
}])
.directive('myCustomer', function() {
    return {
        restrict: 'E',
        scope: {
            param: '='
        },
        template: '<div id="{{param}}"></div>',
        link: function(scope,element,attrs){
            scope.$watch('param',function(){
                console.log(document.getElementById(param)); //get the dom
            });
        }
    };
});
  • Possible duplicate of [AngularJS - Access isolated scope in directive's link function](http://stackoverflow.com/questions/17111016/angularjs-access-isolated-scope-in-directives-link-function) – Ramesh Rajendran Dec 28 '16 at 09:32
  • @RameshRajendran partly,if I bind an object to isolated scope,$attr seems not working. – Vamcheryl Zhang Dec 29 '16 at 10:25

2 Answers2

2

try not to use the data="" since this is a reserved attribute

see https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes for more info about this.

edit: data- will be removed from the attribute. So you can use the data- but you have to add an identifier for your code.

so if you change your html to data-identifier="id"

and in your directive declare the scope like scope: { identifier: '=' } you should be fine

Donniewiko
  • 1,427
  • 1
  • 8
  • 9
2

You can pass your someValue using scope.

In template:

parameter="someValueCanPassTo"

In directive:

scope: {
    parameter: '='
},
link: function(scope, element, attrs) {
    $watch('parameter', function() {
        element.attr('my-attr', scope.parameter);
    });
}
Karthick Nagarajan
  • 1,327
  • 2
  • 15
  • 27