【问题标题】:In angular, the attribute value does not work in an input field在角度中,属性值在输入字段中不起作用
【发布时间】:2015-09-14 07:04:22
【问题描述】:

我只是通常使用输入标签,我想插入一些已经带有值标签的文本,但它不起作用,这是我的代码行:

<input class="form-control input-sm" value="14" type="number" ng-model="textLetterGrootte">

据我所知,我没有做错任何事。

【问题讨论】:

    标签: html css angularjs input


    【解决方案1】:

    如果您使用 AngularJs ngModel 指令,请记住 值属性不绑定在ngModel字段上。你必须自己初始化它,最好的方法是DEMO

    <input class="form-control input-sm" type="number" ng-model="textLetterGrootte"  ng-init="textLetterGrootte=14">
    

    【讨论】:

    • 请解释为什么这样做是为了帮助其他人。 ng-init 是什么意思以及为什么仅使用 value attr 是不够的。
    • 当我想显示文本而不是数字时如何使用 ng-init ?
    • @SVK 抱歉,ng-init="textKleur="SOMETEXT"" 似乎不起作用。
    • 使用单引号 .ng-init="textKleur='SOMETEXT' " @Goldenowner
    【解决方案2】:

    即使你已经接受了答案,让我把它说出来,以便你深入理解它。官方documentation 表示 ng-init 将采用任何表达式。所以是的,只要关联的作用域定义了一个名为 init() 的函数或直接分配初始值,你就可以在上面做你想做的事。

    这个指令可以被滥用来添加不必要的逻辑量 你的模板。 ngInit 只有少数合适的用法,例如 至于 ngRepeat 的别名特殊属性,如演示中所见 以下;以及通过服务器端脚本注入数据。除了这些 在少数情况下,您应该使用控制器而不是 ngInit 来初始化 范围内的值。

    因此,您可以在创建控制器时简单地初始化变量。所以根本没有必要使用 ng-init。 例如:

     var myApp = angular.module('myApp', []);
    
     myApp.controller('myController', ['$scope', function($scope){
    
      $scope.init = function() {
          $scope.textLetterGrootte = 14;
      };
      // runs once per controller instantiation
      $scope.init();
    }]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-26
      • 2016-03-08
      • 1970-01-01
      相关资源
      最近更新 更多