Search code examples
jqueryangularjsangular-directive

How to update the scope value using the custom element click event?


In my directive i am replacing the template according to the index values. when user click on the template, I need to assign the clicked directive value to the scope value.

I can't able to directly call the scope here in replaced element. how to handle this scenario?

here is my directive code :

var allAppsGallery = function ($compile) {

    return {

        replace : true,

        scope : {
            index : "=",
            app : '='
        },

        link : function (scope, element, attrs) {

            var getTemplate = function (index, app) {

                switch (index) {

                    case 0  :
                    case 13  :
                    case 14  :
                    case 15  :
                    case 5 :

                        return $('<div />', 
                                    {
                                        class:'bgr box'+index,
                                        html : '<h2>'+app.completion+'%</h2><span>'+app.name+'</span>',
                                        click : function () {
                                            alert("hi"); //click works here
                       //but how to update the scope variable?
                                        }
                                    }
                                );

                        break;


                }

            }


            element.html(getTemplate(scope.index, scope.app));
            $compile(element.contents())(scope);
            element.replaceWith(element.contents());

            element.click(function(event) { //click event not works.

                scope.activeApp = scope.app; //the new value on click need to update
                scope.$appy();

            });



        }

    }

}

Here is a live demo:

LIVE DEMO FOR TEST


Solution

  • Better way is to bind ng-click before you compile element:

    case 5:
        return '<div class="bgr" ng-class="\'box\' + index" ng-click="action()">' +
                   '<h2>{{app.completion}}</h2><span>{{app.name}}</span>'
               '</div>';
    

    ...

    scope.action = function () {
        scope.activeApp = scope.app;
    };
    

    Updated demo