AngularJS - 是否可以在链接或编译中更改指令上的 ngModel 属性值? [英] AngularJS - Is it possible to change the value of ngModel attribute on directive in link or compile?

查看:23
本文介绍了AngularJS - 是否可以在链接或编译中更改指令上的 ngModel 属性值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个指令,该指令将根据属性值将 ngModel 属性添加到标记中.例如:

I am trying to create a directive that will add an ngModel attribute to a tag based on the attribute value. For example:

angular.module('myModule').
  directive('myDirective', function() {
    return {
      link: function(scope, elem, attrs) {
        var modelName = 'myPrefix.' + attrs.name;
        attrs.$set('ngModel', modelName);
      }
    };
  });

所以这个html:

<input name="foo" my-directive></input>

被编译成

<input name="foo" ng-model="myPrefix.foo" my-directive></input>

它接受输入的名称,附加一个前缀,并将 ngModel 属性设置为该值.

It takes the name of the input, attaches a prefix, and sets the ngModel attribute to that value.

当我尝试在链接函数中执行此操作时,似乎 input 未在 formController 中注册,因此 form.foo 返回 undefined.

When I try to do this in the link function, it seems like the input isn't being registered with the formController, so that form.foo returns undefined.

是否有可能完成我想要做的事情?

Is it possible to accomplish what I'm trying to do?

似乎在 HTML 上设置了 ngModel 属性,但它没有在表单中注册,或者 ngModelController 没有被实例化.如果我查看范围内ngModel的值,修改输入时它不会改变.

It seems like the ngModel attribute is being set on the HTML, but it is not being registered with the form, or the ngModelController is not being instantiated. If I look at the value of ngModel in the scope, it does not change when I modify the input.

推荐答案

我能够通过使用模板函数来实现目标.我认为它在链接函数中不起作用,因为它发生在收集了所有指令之后,因此编译器无法识别添加了 ngModel 指令.不过,我不确定为什么它在 compile 函数中不起作用(即使我将优先级设置为 100).

I was able to accomplish the goal by using a template function. I think it doesn't work in the link function because it occurs after all of the directives have been collected, so the compiler doesn't recognize that an ngModel directive has been added. I'm not sure why it doesn't work in the compile function, though (even if I set the priority to 100).

这是指令的工作版本:

angular.module('myModule').
  directive('myDirective', function() {
    return {
      replace: true,
      template: function(elem, attr) {
        var newElem = '<input ng-model="model.' + attr.name + '">';
        return newElem;
      }
    };
  });

这篇关于AngularJS - 是否可以在链接或编译中更改指令上的 ngModel 属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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