2016-05-16 103 views
1

这里是我的HTML代码:NG单击不起作用

<section ng-controller="GalleryController as gallery"> 
    <nav footer-directive></nav> 
</section> 

控制器:

angular 
    .module('myapp') 
    .controller('GalleryController', GalleryController); 

    GalleryController.$inject = ['GalleryService']; 

    function GalleryController(GalleryService){ 
    var self=this; 
    self.current_index=0; 

    self.leftArrow=function(){ 
     if (self.photos.length!==0){ 
      if (self.current_index===0) { 
       self.current_index=self.photos.length-1; 
      } else { 
       self.current_index--; 
      } 
      self.selected_photo=self.photos[self.current_index]; 
     } 
    }; 

    self.rightArrow=function(){ 
     if (self.photos.length!==0){ 
      if (self.current_index===self.photos.length-1) { 
       self.current_index=0; 
      } else { 
       self.current_index++; 
      } 
      self.selected_photo=self.photos[self.current_index]; 
     } 
    }; 

    self.searchResults=function(){ 
     return GalleryService.getPhotos(self.search_tag,self.page).then(function() { 
      self.photos = GalleryService.photos; 
      self.selected_photo=self.photos[0]; 
      var total=GalleryService.total_photos_number; 
      self.total_pages=total%15===0 ? total/15 : (total-total%15)/15+1; 
     }); 
    }; 

    self.searchResults(); 
    } 

和指令footerDirective

angular 
    .module('myapp') 
    .directive('footerDirective', footerDirective); 
function footerDirective(){ 
    return { 
     link: function(scope,elements,attributes){ 
       var new_div=document.createElement("div"); 
       new_div.setAttribute("ng-click", "gallery.leftArrow()"); 
       new_div.innerHTML=content; 
       new_div.className=cname; 
       elements[0].appendChild(new_div); 

     } 
    } 
    } 

为什么NG-点击不适用于new_div?

+1

因为你没有编译它!在setAttribute之后使用'$ compile'。 – Bettimms

+0

你介意写下确切的命令吗? –

回答

1

使用$compile应该工作

$compile(new_div)(scope) 
+0

如果我在函数内写入'$ compile is not defined' –

+1

在指令中注入$ complie。 –

+1

[此链接](http://stackoverflow.com/questions/25759497/angularjs-dynamically-set-attribute)可能有帮助 –