如何用ng-model在输入字段中显示值?

时间:2018-04-06 10:22:56

标签: angularjs angularjs-1.6

我创建了编辑表单,因此我必须为每个文本字段包含默认值。我写了这个HTML代码:

<input type="text" ng-model="projectData.title" ng-init="projectData.title=title" name="title" class="form-control" />

在控制器中:

$scope.title = "This is just title";

它在文本框中没有显示任何内容。我尝试了ng-init="projectData.title={{title}}"ng-init="projectData.title='title'",但它没有用。

我正在使用angularjs 1.6,以下解决方案也不起作用。

http://jsfiddle.net/Aejvm/337/

4 个答案:

答案 0 :(得分:0)

Check This [Code][1]
  [1]: http://jsfiddle.net/d4ts76ys/

使用该对象将其映射到ng-model

答案 1 :(得分:0)

在您的范围内,您应该声明对象:

$scope.projectData = {};
$scope.projectData.title = "This is just title";

答案 2 :(得分:0)

嗯,你做错了。

ng-init是angular指令,你不需要大括号。

将您的代码修改为:  HTML:

 <div ng-controller="MyCtrl">
<input type="text" ng-init="rootFolders.name=name" ng- 
    model="rootFolders.name"  >
 <br>rootFolders={{name}}
   </div>

JS:

var app = angular.module('myApp',[]);
 app.controller('MyCtrl', function($scope) { 
   $scope.name = "Acunisasi";
  });

答案 3 :(得分:0)

I have created fiddle that may help your

jsfiddle

//html
<div ng-controller='MyCtrl'>
  <form>
    <input ng-init="projectData.title = title" type="text" ng-model="title">
        <button ng-click="formSubmit()">
        submit
        </button>
  </form>
  {{title}}
</div>

//js

 var app = angular.module('myApp', []);
 app.controller('MyCtrl', ['$scope', MyController]);

 function MyController($scope) {
   $scope.projectData = {};
   $scope.title = 'This is just title';

   $scope.formSubmit = function() {
     console.log("$scope.projectData  ===>", $scope.projectData)
   }
 }