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

查看:112
本文介绍了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);
      }
    };
  });

让这个网站:

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

被编译成

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

这需要输入的名称,附加一个preFIX,并设置ngModel属性到该值。

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

当我尝试这样做在链接功能,这似乎是在输入未与表单控制器中注册,所以形式包含.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?

编辑:

这似乎是 ngModel 属性正在上的HTML设置,但是它没有被与表单注册,或者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 指令已添加。我不知道为什么它不会在编译功能正常工作,但(即使我的优先级设置为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).

下面是该指令的工作版本:

Here's the working version of the directive:

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天全站免登陆