用函数初始化ng-model字符串

Initialize ng-model string with function

本文关键字:字符串 ng-model 初始化 函数      更新时间:2023-09-26

是否有一种方法可以有条件地初始化ng-model为具有函数的特定字符串?下面,ng-bind可以工作,但ng-model不行:

var app = angular.module('app', []);
app.controller('mainCtrl', ['$scope', function ($scope) {
  $scope.value = "hello";
  $scope.value2 = "hello2";
  $scope.get = function (bool) {
      return (bool) ? "value" : "value2";
  };
}]);
<html ng-app="app">
  <body ng-controller="mainCtrl">
    <div ng-bind="{{get(true)}}"></div>
    <input ng-model="{{get(true)}}" />
  </body>
</html>

澄清编辑:我有两个独立的数据集,一个给定的输入可以影响它们。它影响哪一个取决于模型中其他地方的值。有几十种不同的输入类型,我想避免在每一种类型中都写ng-switch,因为那样会变得相当混乱。

例子: http://plnkr.co/edit/fKlbN8qcjGjzqjRayviT?p =预览

这是有条件设置模型值的最干净、最简单的方法。

<input ng-model="yourModel" /> then in controller:

$scope.yourModel = (condition) ? 'hello1' : 'hello2';

编辑澄清问题

好的,我想出了一些使用ng-init。显然,您不能对ng-model使用函数。我还没有尝试过,所以我很惊讶它没有工作。

我放弃了自定义指令,因为它不需要。

你的HTML应该是这样的:

<div ng-init="input1 = getBinding(setB,2)">
  <input ng-model="input1" /> <!-- shows bbb -->
</div>
<div ng-init="input2 = getBinding(setA,0)">
  <input ng-model="input2" /> <!-- shows a -->
</div>
<div ng-init="input3 = getBinding(setA,2)">
  <input ng-model="input3" /> <!-- shows aaa -->
</div>

你的控制器:

app.controller('mainCtrl', ['$scope', function ($scope) {
  $scope.setA = ['a', 'aa', 'aaa'];
  $scope.setB = ['b', 'bb', 'bbb'];
  $scope.getBinding = function(set, index)
  {
    return set[index];
  }
}]);

所以继续,而不是像input1 = ..., input2 = ...等设置名称,如果你要使用一个重复器,你可以使用$index值来创建模型名称,像这样:

<div ng-repeat="setItem in setA" ng-init="setA$index = getBinding(setA, $index)">
  <input ng-model="setA$index" /> <!-- shows 3 inputs of values a, aa, aaa -->
</div>
<div ng-repeat="setItem in setB" ng-init="setB$index = getBinding(setB, $index)">
  <input ng-model="setB$index" /> <!-- shows 3 inputs of values b, bb, bbb-->
</div>

DEMO - http://plnkr.co/edit/70QG3s3ovppkXcUqOmPj?p=preview

希望你能找到自己的解决方案。

假设出于某种原因,您需要在视图中执行此操作,您可以使用init将变量设置为get函数的返回值,并将模型设置为该值

<div ng-controller="MyCtrl">
    <input ng-model="whatever.value" ng-init="whatever = get(true)" />
    {{var1}}
    {{whatever}}
</div>
function MyCtrl($scope) {
    $scope.var1 = { value: "hello" };
    $scope.var2 = { value: "hello2" };
    $scope.get = function (bool) {
        return (bool) ? $scope.var1 : $scope.var2;
    };
}
http://jsfiddle.net/dPn3A/

你可以这样使用ngInit:

  <body ng-controller="MainCtrl" ng-init="titel=get(true)">
    <div ng-bind="titel"></div>
    <input ng-model="titel" />
  </body>