0

Привет Я новичок на угловых.Angularjs: -Как вызвать действия контроллера с помощью директивы

Я хотел бы реализовать код, где, когда я нажимаю на кнопку, я должен быть в состоянии сделать api-вызов и отображать данные внутри HTML.

Теперь я реализовал директиву, и HTML сгенерирован, но, когда я нажимаю на значок или напоминание, он не работает.

В контроллере называется usercontroller (у него много других функций). Однако я не очень уверен, как вызвать контроллер, только для особого значка.

Внизу директива я написал: -

'use strict'; 
var pageno=1; 

function MainCtrl($scope) { 
    $scope.count = 0; 
} 

//Directive that returns an element which adds buttons on click which show an alert on click.Here we can put 
woi.directive("yes",['userAPI','$rootScope', function(userAPI,$rootScope){ 

    return { 
     restrict: "E", 
     template: "<button ng-click='str()' addbuttons>please click for Top Rated</button>" 



//Directive for adding buttons on click that show an alert on click 
woi.directive("addbuttons",['$rootScope','userAPI','$compile','$filter', function($rootScope,userAPI,$compile,$filter,){ 
    return function(scope, element, attrs){ 
     element.bind("click", function(){ 
     // var pageno=1; 
      scope.count++; 
      var pageno=1; 
      pageno++; 
      scope.pageNo=pageno; 
      //var abc= scope.loadRated(pageno); 
      userAPI.topRated({userid: $rootScope.getUser().userid,pageno:pageno}, function (r, $scope, div){ 
       if(!$rootScope.device.isMobile && !$rootScope.device.isTablet && !$rootScope.device.isTouch) { 
        var topRatedList = r.gettopratedhomepage.topratedprogrammelist; 
        console.log(r) 


        var str=''; 
        if(r !=null && r.gettopratedhomepage!=null && r.gettopratedhomepage.topratedprogrammelist!=null) 
         if(r.gettopratedhomepage.topratedprogrammelist.length>0){ 

          for(var i=0;i<topRatedList.length;i++) 
          { 
           // str+="topRatedList[i].actualname"; 

           var programNameEncode=$filter('encodeUrl')(topRatedList[i].programmename); // | encodeUrl; topRatedList[i].programmename; 
           var program=topRatedList[i].programmename; 
           var channelId=topRatedList[i].channelid; 
           var programId=topRatedList[i].programmeid; 
           var channel=topRatedList[i].channeldisplayname; 
           var channelNameEncode=$filter('encodeUrl')(topRatedList[i].channeldisplayname)  //| encodeUrl; 
           // var startTime=topRatedList[i].starttime; 
           var favourite=topRatedList[i].isfavorite; 
           var reminder=topRatedList[i].isreminder; 
           var watchlist=topRatedList[i].iswatchlist; 
           var duration=topRatedList[i].duration; 
           var imageFile=topRatedList[i].imagefilepath; 
           var startTime = $filter('featuredVideoTime')(topRatedList[i].starttime) ;    // featured video time 
           var duration= topRatedList[i].duration; 
           var isReco=topRatedList[i].isrecommended;   // This is for reco 

           var genre=topRatedList[i].channelgenre; 
           var imagefilepath=topRatedList[i].imagefilepath; 
           var logo= topRatedList[i].logofileurl; 

           var p={ 

            $$hashKey: "10Z", 
            actualname: "program", 
            channeldisplayname: "channel", 
            channelgenre: "genre", 
            channelid: "channelId", 
            channellogo: "logo", 
            channelname: "channel", 
            channelweburl: null, 
            contextualtext: "Rated for You", 
            endtime: "2014-10-07T12:15:00", 
            genre: "genre", 
            imagefilepath: "imagefilepath", 
            ischeckin: "0", 
            isfavorite: "0", 
            isrecommended: "0", 
            isreminder: "0", 
            iswatchlist: "0", 
            isyoutube: topRatedList[i].isyoutube, 
            keywords: null, 
            languagename: "English", 
            // logofileurl: logo, 
            programmeduration: "50", 
            programmeid: "", 
            programmename: "New Tricks", 
            reminderid: "0", 
            rownumber: "2", 
            serialno: "0", 
            starttime: "2014-10-07T11:25:00", 
            synopsis: "To put her flagging police career back on track, Sandra Pullman hires three old veterans to lend a helping hand.", 
            timestring: "11:25 AM, Tomorrow", 
            totalcheckincount: "0", 
            totalprogramfavcount: "13", 
            totalremindercount: "34" 

           } 


           str+=" <div class='item' style='display: block;' >" ; 
           str+="<div class=\"thumb\">"; 
           //  str+="<div ng-show=\""+isReco=='1'+"\" class=\"favorite-ribbon\"></div>"; 
           str+="<div class=\"player\"></div>"; 
           str+="<div class='image' >"; 
           str+="<img src='"+imageFile+"' style='width:100%;height:100%;'/>"; 
           str+="<a ng-click=\'playVideo("+program+"\,$event)' ng-show='hasVideo()' class='play' style='cursor:pointer'></a>"; 

           str+="<a ng-href=\"#!/program/"+programNameEncode+"\" ng-show=\"!hasVideo()\" class=\"noPlay\" style='position: absolute;top: 0;left: 0;' ng-click=\"EncodeUrlWithDash("+program+",$event,'programme',"+channelId+","+programId+","+startTime+")\"></a></div>"; 

           str+="<span class='time' ng-show='duration'>\""+duration+"\"</span>"; 

           str+="<div class='user-actions' ng-controller='UserController'>"; 

           str+="<a live-tooltip='Add to Favorite' ng-click='toggleFavorite("+topRatedList+", $event)' class='btn btn-small btn-purple-blue' ng-class=\""+{active:favourite == '1'}+"\">"; 
           str+="<i class='icon-favorite'></i></a>"; 

           str+="<a live-tooltip='Reminder Alerts' ng-click='toggleReminder("+topRatedList+", $event)' class='btn btn-small btn-purple-blue' ng-class=\""+{active:reminder == '1'}+"\">"; 
           str+="<i class='icon-reminder'></i></a>"; 

           str+="<a live-tooltip='Add to Watchlist' ng-click='addToWatchlist(p, $event)' class='btn btn-small btn-purple-blue' ng-class=\""+{active:watchlist == '1'}+"\">"; 
           str+="<i class='icon-watchlist'></i></a></div>"; //end of user controller div 

           str+="</div>"; // end of thumb div 

           str+="<div class='text-wrapper'>"; 
           str+="<h2 multiline-overflow><a title='"+program+"' href='#!/program/"+programNameEncode+"' ng-click=\""+"EncodeUrlWithDash(\""+program+"\",$event,'programme',\""+channelId+"\",\""+programId+"\",\""+startTime+"\")"+"/ >"+program+"</a></h2>"; 

           str+="<p class='infoChannel' live-tooltip-single-line= '"+channel+"'><a href='#!/channel/"+channelNameEncode+"' ng-click=\""+"EncodeUrlWithDash(\""+channel+"\",$event,'channel',\""+channelId+"\",\""+programId+"\")"+"/ >"+channel+"</a></p>"; 
           str+="<p class='info'>"+startTime+"</p>"; 

           str+="</div></div>"; //end of the main div 

           //EXTRA LINE 
           //   str+=" <div class='item' ng-repeat='topRatedList[i] in programs.rated' home-tab-item watchable='topRatedList[i]' ></div>" ; 

           //   angular.element(document.getElementById('space-for-buttons')).append($compile(str)(scope)); 

          }   // For loop end here..Declaration 

         } 
         else{ 

          str="No data found"; 
         } 

        angular.element(document.getElementById('space-for-buttons')).append($compile(str)(scope)); 



        // The above code is required to append data into the division(loadrated).. 

       } 
      }); 

     }); 
    }; 
}]); 

Я создал строку, и я создания HTML для программ, которые будут созданы.

Может кто-то пожалуйста, помогите мне с this.Thanks

ответ

0

Если вы хотите вызвать действие контроллера из директивы при нажатии на кнопку после отображения определенного сообщения, вы можете установить действия и сообщения в качестве параметров в директиве. попробуйте этот

'use strict'; 

angular.module('directives') 
    .directive("MyButton", function(){ 
     return{ 
      restrict: "E", 
      replace: true, 
      link :function(scope, element, atts){ 
        var buttonText = "<button class='btn btn-primary'>click</button>"; 
        element.html(buttonText); 
        element.on("click", function(){ 
         var result = confirm(atts.message); 
         if(result) 
         { 
          scope.$apply(atts.action); 
         } 
        }); 
      } 
     } 
    }); 

, а затем вы можете установить параметры в директиве этого пути

<my-button message="Are you sure?" action="delete"></my-button> 
+0

@ Сафаа-elgendi..Thanks для info..However я хочу сделать апи вызов с помощью параметра и получить результат, когда я нажимаю кнопку. Можем ли мы реализовать это – Catmandu