【问题标题】:How to update the scope value using the custom element click event?如何使用自定义元素点击事件更新范围值?
【发布时间】:2015-09-14 04:35:49
【问题描述】:

在我的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

【问题讨论】:

  • $scope.activeApp = app; 实际上我想在这里更新app。范围变量名称是`$scope.activeApp'

标签: jquery angularjs angular-directive


【解决方案1】:

更好的方法是在编译元素之前绑定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

【讨论】:

猜你喜欢
  • 2016-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多