2016-12-28 61 views
1

在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? 谢谢!


使用范围$腕表解决的问题:

在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 
      }); 
     } 
    }; 
}); 
+0

的可能的复制[AngularJS - 在指导的链接功能访问隔离范围(http://stackoverflow.com/questions/17111016/ angularjs-access-isolated-scope-in​​-directives-link-function) –

+0

@RameshRajendran部分地,如果我将一个对象绑定到独立的作用域,$ attr似乎不起作用。 –

回答

3

可以使用范围传递你someValue中。

模板:

parameter="someValueCanPassTo" 

在指令:

scope: { 
    parameter: '=' 
}, 
link: function(scope, element, attrs) { 
    $watch('parameter', function() { 
     element.attr('my-attr', scope.parameter); 
    }); 
} 
+0

谢谢!范围。$ watch()的作品! –

+1

欢迎您@VamcherylZhang投我一票,接受我的回答.. –

+0

你在那里@VamcherylZhang –

2

尽量不要使用data=""因为这是一个保留属性

有关更多信息,请参阅https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes

编辑: data-将从属性中删除。所以你可以使用数据 - 但你必须为你的代码添加一个标识符。

所以如果你改变你的HTML data-identifier="id"

,并在你的指令声明像scope: { identifier: '=' }范围你应该罚款

+0

谢谢!我会关注这一点。使用范围。$ watch()在链接函数中解决了这个问题。 –