如何通过angularjs将JS事件添加到动态创建的元素中

时间:2017-08-16 13:01:35

标签: javascript angularjs

我创建了一个angularjs指令,它返回2个div,我有动画。当我在html页面上呈现指令时,我能够看到这些指令但是,我无法选择具有id的元素。当我选择带有id的元素时,我将获得空值。

我该如何解决这个问题?这是我的片段。



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

application.directive('newsfeeds', function() {
  return {
    restrict: 'E',
    template: `
    			<div id="reveal-button"><<</div>
    			<div class="reveal-content"></div>
    		`
  }
})
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();
  }
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:-1)

在HTML文件中提及此行。

&#13;
&#13;
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();
        }       
    })

  
});
    
&#13;
<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>
&#13;
&#13;
&#13;