如何动态添加ng-change处理程序到输入 [英] how to add ng-change handler dynamically to input

查看:28
本文介绍了如何动态添加ng-change处理程序到输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

app.directive('textForm', function ($compile) {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: "textForm.html",
        scope: {
            label: "@",
            model: "=",
            type: "@",
            name: "@",
        },
        link: function (scope, element) {
            scope.log = function () {
                console.log(1);
            };

            var input = element.find('.form-control');
            input.attr({'ng-change': 'log()'});
            $compile(element.contents())(scope);
        }
    }
});

<!-- this is textForm.html -->
<div class="form-group">
    <label class="col-xs-3 control-label">{{label}}</label>
    <div class="col-xs-7">
        <input type="{{type||'text'}}" name="{{name}}" class="form-control" ng-model="model">
    </div>
</div>

<!-- this is how I use the directive -->
<text-form label="name" name="name" model="person.name"></text-form>

上面的代码无法运行,但可以说明问题.

the above code couldn't run, but can tell the problem.

出于某种原因,我想将 ng-change 动态地添加到 input 中,经过一番搜索,我发现 $ compile 可以做到这一点.但这似乎行不通,我也不知道为什么.

I want to add ng-change to input dynamically for some reason and after some search I found $compile could do this. But it seems doesn't work and I don't know why.

我的棱角版本是1.5.5

My angular version is 1.5.5

推荐答案

我认为问题是您正在编译 text-form 元素(由指令赋予),但是您要附加ng-code属性更改为 .form-control 元素(甚至不是指令的子元素).因此,angular没有意识到这一点,也没有正确整合ng-change.

I think the problem is that you are compiling the text-form element (given by the directive), but you append the ng-change attribute to the .form-control element (which is not even a child of your directive). So angular is not aware of this and does not integrate the ng-change properly.

我认为您应该在要以这种方式控制的元素上使用此指令,即:

I think you should use this directive on the element you want to control this way, i.e.:

<input text-form type="{{type||'text'}}" name="{{name}}" class="form-control" ng-model="model">

并将指令限制为"A"或"AE"

and make the directive restrict to 'A' or 'AE'

不确定,但是如果您将指令放在父项(例如form元素)上,我认为这也会起作用.

Not sure, but I think it would also work if your directive is placed on a parent (e.g. the form element).

这篇关于如何动态添加ng-change处理程序到输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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