从自定义指令触发ngChange [英] Trigger ngChange from custom directive

查看:120
本文介绍了从自定义指令触发ngChange的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取自定义指令以激活ngChange事件,以使原始控制器在指令中的数据发生更改时执行某些操作.

I'm trying to get my custom directive to activate a ngChange event in order for the original controller to do something when data has changed in the directive.

我的指令如下:

.directive('spInputCheckbox', function() {
        return {
            scope: {
                ngModel: '=',
                ngChange: '&'
            },
            restrict: 'AE',
            replace: 'true',
            template: '<div><span ng-click="model = !model"><i ng-if="model">X</i></span><input type="checkbox" ng-model="model" ng-change="change(model)" /><span ng-if="title">{{ title }}</span></div>',
            link: function(scope, elem, attr){
                    scope.title = attr.title
                scope.$watch('ngModel', function(value){
                    if(value){
                        scope.model = scope.ngModel
                    }
                });

                scope.change = function(value){
                    scope.ngModel = scope.model
                    scope.ngChange()
                }
            }
        };
    })

这就是我的称呼方式

<sp-input-checkbox ng-model="info"
      ng-init="info = false"
      title="click me"
      ng-change="alert(7)" />

这是带有代码的 JsFiddle

推荐答案

也许看着模型可以完成您想要实现的目标

Maybe watching the model can do what you want to achieve like this

scope.$watch('model', function(value){
    if(value){
        scope.ngModel = scope.model
        hasChange = true
    }

    if(hasChange) {
             scope.change()
    }
});

此处

这篇关于从自定义指令触发ngChange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆