AngularJS - 将ng-model绑定到一个名称存储在另一个变量中的变量

Bru*_*uno 14 javascript angularjs

我正在尝试将输入字段的值绑定到变量.我不知道这个变量的名称是先验的 ; 它存储在另一个变量中.

这是html:

<body ng-controller="stageController">
    <form name="myForm" novalidate="">
        <input type="text" name="myText" ng-model="model" />
    </form>
</body>
Run Code Online (Sandbox Code Playgroud)

这是控制器:

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';
}
Run Code Online (Sandbox Code Playgroud)

我也是个小提琴.

这不起作用,因为当前绑定在输入字段和model变量之间.相反,我会将输入字段绑定到变量名称存储在$scope.model变量中的变量(在本例中realModel).

可能吗?怎么样?

小智 19

是的,它可能.我不明白你为什么要这样做,但我可以告诉你如何做.我无法启动小提琴,但我复制到了一个plnkr:http://plnkr.co/edit/o1gFf1lMq4Pg5iVoVyUN?p = preview

您创建一个指令,使用$ compile将原始模板转换为新模板.新指令:

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])
            }
        }
    }
})
Run Code Online (Sandbox Code Playgroud)

更新了html(从ng-model更改为ng-bind-model,新指令)

<input type="text" name="myText" ng-bind-model="model"  />
Run Code Online (Sandbox Code Playgroud)

  • 创建一个名为ngXxx的指令是一种不好的做法("不要为你自己的指令添加前缀,否则它们可能与Angular的未来版本中包含的指令冲突" - [doc](http://docs.angularjs.org/guide/指令)) (15认同)

MiM*_*iMo 13

一个更简单的替代方案 - 前提是可以稍微改变模型 - HTML:

<body ng-controller="stageController">
    <form name="myForm" novalidate="">
        <input type="text" name="myText" ng-model="vars[model]" />
    </form>
</body>
Run Code Online (Sandbox Code Playgroud)

模型:

function stageController($scope) {
    $scope.model = 'realModel'; // contains the name of the variable that i would bind   to the field 
    $scope.vars = {};    // variables container
    $scope.vars.realModel = 'initial value of the field';
}
Run Code Online (Sandbox Code Playgroud)

  • 最好的答案IMO (3认同)

小智 9

我尝试使用之前的答案ng-repeat,但它没有用.它使用compile函数,这意味着所有指令都使用了最后传入的值.如果你使用链接功能它似乎按预期工作,即

.directive('ngBindModel',function($compile){
      return{
        link:function(scope,element,attr){
          element[0].removeAttribute('ng-bind-model');
          element[0].setAttribute('ng-model',scope.$eval(attr.ngBindModel));
          $compile(element[0])(scope);
        }
      };
    })
Run Code Online (Sandbox Code Playgroud)