2016-12-28 60 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()在鏈接函數中解決了這個問題。 –