【发布时间】:2016-12-28 09:25:26
【问题描述】:
在 html 中,我在指令中绑定 id:
<my-customer data="id"></my-customer>
在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'));
}
};
});
它可以在模板中显示数据,但控制台显示未定义,因为模板尚未加载数据,我如何在数据加载后获取 dom? 谢谢!
使用scope.$watch解决问题:
在 html 中:
<my-customer param="id"></my-customer>
在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
});
}
};
});
【问题讨论】:
-
@RameshRajendran 部分,如果我将对象绑定到隔离范围,$attr 似乎不起作用。
标签: javascript angularjs angularjs-directive