AngularJS:如何将默认值设置为ng-model ="searchText"?

Sac*_* R. 18 html angularjs

我无法将默认值设置为ng-model ="searchText".这是我正在使用的代码
<input ng-model="searchText" value="can you see me" />

谁能帮我这个?

Mar*_*rif 34

第一个解决方案:简单地在控制器中初始化searchText.

App.controller('mainController',['$scope', function($scope) {
   $scope.searchText  = "can you see me";
}]);
Run Code Online (Sandbox Code Playgroud)

第二个解决方案:是使用ng-init insteat的值

<input ng-model="searchText" ng-init="searchText ='can you see me'"></input>
Run Code Online (Sandbox Code Playgroud)


Ash*_*hta 10

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="">
<div >
  <input ng-model="searchText" type="text" ng-init="searchText='your text'"/>
</div>  
  </div>  
Run Code Online (Sandbox Code Playgroud)

您可以使用 ng-init


car*_*ton 5

请尝试以下代码:

     <input ng-model="searchText" ></input>
Run Code Online (Sandbox Code Playgroud)

在你的控制器中

    $scope.searchText = "your default value";
Run Code Online (Sandbox Code Playgroud)

编辑:如果你不想初始化控制器中的默认值就行了

      <input value="your default value" ></input>
Run Code Online (Sandbox Code Playgroud)

  • 你可以用两种方式做到这一点.一个是使用一个控制器,另一个是直接指定它.上面的方法是最好的方法来做到这一点 (2认同)