2017-08-16 77 views
-2

我已經創建了一個angularjs指令,該指令返回2個具有動畫的div。當我在html頁面上顯示指令時,我能夠看到這些指令,但是我無法選擇帶有id的元素。當我選擇帶有ID的元素時,我得到空值。如何通過angularjs將JS事件添加到動態創建的元素

我該如何解決這個問題?這是我的片段。

var application = angular.module('newsfeed', []) 
 

 
application.directive('newsfeeds', function() { 
 
    return { 
 
    restrict: 'E', 
 
    template: ` 
 
    \t \t \t <div id="reveal-button"><<</div> 
 
    \t \t \t <div class="reveal-content"></div> 
 
    \t \t ` 
 
    } 
 
}) 
 
var slideContainer = document.getElementById('slide-container'); //selecting the element 
 
var slideButton = document.getElementById('reveal-button'); //selecting the element 
 
var slideopen = false; 
 

 
console.log(slideButton); //logging the output to console returns null 
 

 
var showslide = function() { 
 
    slideContainer.style.right = '0px' 
 
} 
 

 
var hideslide = function() { 
 
    slideContainer.style.right = '-350px' 
 
} 
 

 
window.addEventListener('slideButton', 'click', function() { 
 
    if (slideopen == false) { 
 
    slideopen = true; 
 
    showslide(); 
 
    } else { 
 
    slideopen = false; 
 
    hideslide(); 
 
    } 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

+0

你在哪裏把這個JavaScript代碼?看起來你完全無視你應該如何做到這一點 – devqon

回答

-1

提到此行到您的HTML文件。

var slideContainer = document.getElementById('slide-container');//selecting the element 
 
    var application = angular.module('newsfeed',[]) 
 

 
application.directive('newsfeeds',function(){ 
 
    return{ 
 
     restrict: 'E', 
 
     template:` 
 
      <div id="reveal-button"><<</div> 
 
      <div class="reveal-content"></div> 
 
     ` 
 
    } 
 
}) 
 
    application.controller('mainController', function($scope,$timeout) { 
 
    var slideButton = document.getElementById('reveal-button'); //selecting the element 
 
    var slideopen = false; 
 

 
    console.log(slideButton); //logging the output to console returns null 
 

 
    var showslide = function(){ 
 
     slideContainer.style.right = '0px' 
 
    } 
 

 
    var hideslide = function(){ 
 
     slideContainer.style.right = '-350px' 
 
    } 
 

 
    window.addEventListener('slideButton','click',function(){ 
 
     if(slideopen == false){ 
 
      slideopen = true; 
 
      showslide();  
 
     } else { 
 
      slideopen = false; 
 
      hideslide(); 
 
     }  
 
    }) 
 

 
    
 
}); 
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div class="container" ng-app="newsfeed" ng-controller="mainController"> 
 
    <newsfeeds></newsfeeds> 
 
</div>

相關問題