【问题标题】:Angularjs:-How to call controller actions with the help of directiveAngularjs:-如何在指令的帮助下调用控制器动作
【发布时间】:2014-11-11 06:02:19
【问题描述】:

您好,我是 angularjs 的新手。

我想实现一个代码,当我点击一个按钮时,我应该能够进行 api 调用并在 HTML 中显示数据。

现在我已经实现了一个指令并生成了 HTML,但是当我点击 favicon 或提醒时,它不起作用。

以下是在名为 usercontroller 的控制器中实现的(它还有很多其他功能)。但是我不太清楚如何调用控制器,仅针对特定的 favicon。

下面是我写的指令:-

'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。

有人可以帮我解决这个问题吗?谢谢

【问题讨论】:

    标签: javascript angularjs model-view-controller angularjs-directive


    【解决方案1】:

    如果您想在显示特定消息后单击按钮时从指令中调用控制器的动作,您可以将动作和消息设置为指令中的参数。试试这个

    '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>
    

    【讨论】:

    • @safaa-elgendi..感谢您的信息..但是我想在参数的帮助下进行 api 调用并在单击按钮时获得结果。我们可以实现这个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多