AngularJS - 绑定NG-模型的变量这名存储另一个变量中 [英] AngularJS - bind ng-model to a variable which name is stored inside another variable

查看:229
本文介绍了AngularJS - 绑定NG-模型的变量这名存储另一个变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想输入字段的值绑定到一个变量。
我不知道这个变量名的先验的;它被存储在另一个变量

I'm trying to bind the value of an input field to a variable. I don't know the name of this variable a priori; it is stored in another variable.

这是HTML:

<body ng-controller="stageController">
    <form name="myForm" novalidate="">
        <input type="text" name="myText" ng-model="model" />
    </form>
</body>

和这是控制器:

function stageController($scope) {
    $scope.model = 'realModel'; // contains the name of the variable that i would bind to the field 
    $scope.realModel = 'initial value of the field';
}

我也做了一个小提琴

I made also a fiddle.

这不起作用,因为当前的结合是输入字段和模式变量之间。相反,我会输入字段到名称存储在 $ scope.model 变量里面的变量(在这种情况下,结合 realModel )。

This doesn't work because currently the binding is between the input field and the model variable. Instead I would bind the input field to the variable which name is stored inside the $scope.model variable (in this case realModel).

这可能吗?怎么样?

推荐答案

是的,其可能的。我不明白为什么你要做到这一点,但我可以告诉你如何。我不能启动小提琴,但我复制到一个plnkr:<一href=\"http://plnkr.co/edit/o1gFf1lMq4Pg5iVoVyUN?p=$p$pview\">http://plnkr.co/edit/o1gFf1lMq4Pg5iVoVyUN?p=$p$pview

Yes, its possible. I dont understand why you'd want to do it, but I can show you how to. I couldnt start the fiddle, but I copied to a plnkr: http://plnkr.co/edit/o1gFf1lMq4Pg5iVoVyUN?p=preview

您创建改造原有的模板到使用$编译一个新的指令。新指令:

You create a directive that transform the original template into a new one using $compile. The new directive:

directive('ngBindModel',function($compile){
    return{
        compile:function(tEl,tAtr){
          tEl[0].removeAttribute('ng-bind-model')
            return function(scope){
              tEl[0].setAttribute('ng-model',scope.$eval(tAtr.ngBindModel))
              $compile(tEl[0])(scope)
                console.info('new compiled element:',tEl[0])
            }
        }
    }
})

更新的HTML(从NG-模式改变NG-绑定模型,新指令)

Updated html (change from ng-model to ng-bind-model, the new directive)

<input type="text" name="myText" ng-bind-model="model"  />

这篇关于AngularJS - 绑定NG-模型的变量这名存储另一个变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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