如何使用自定义元素点击事件更新作用域值?

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

在我的 directive 中,我正在根据 index 值替换模板。当用户点击模板时,我需要将点击的 directive 值分配给 scope 值。

我无法在 replaced 元素中直接调用此处的 scope。如何处理这种情况?

这是我的 directive 代码:

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();

            });



        }

    }

}

这是一个现场演示:

LIVE DEMO FOR TEST

更好的方法是在编译元素之前绑定 ng-click

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