使用$ scope变量自动设置字段 - AngularJS

时间:2014-09-30 10:44:56

标签: javascript angularjs angularjs-scope

填写文本字段并预先选择下拉列表时遇到问题。

这是我的角度代码。

angular.module('MyCtrl', [])


    .controller('myController', ['$scope','$http', function($scope,$http) {
                $scope.user = {};
                $scope.master = {};
            $scope.user.name='Fahad'; //this text field and is not working
            $scope.user.gender='Male'; //this is select and also not working

      $scope.update = function(user) {
           //... some code that take all the user fields and update to DB
       };
      $scope.reset = function() {
         $scope.user = angular.copy($scope.master);
      };
     $scope.reset();
    }]);

HTML:

<input type="text" ng-model="user.name" name="uName">
<select ng-model="user.gender" name="mType" required>
   <option value="Male" selected="selected">Male</option>
   <option value="Female">Female</option>
</select>

其他一切都很好。 update函数获取所有文本字段并更新,

但出于某种原因,我需要预先填写一些字段。

感谢hlep。

1 个答案:

答案 0 :(得分:1)

问题出在第一行,您正尝试使用ng-Model引导角度。它应该是ng-app并且在那之后完全适合:)

HTML代码:

//Over here change ng-model to ng-app
<div ng-app="MyCtrl">
    <div ng-controller="myController">
        <input type="text" ng-model="user.name" name="uName">
        <select ng-model="user.gender" name="mType" required>
            <option value="Male" selected="selected">Male</option>
            <option value="Female">Female</option>
        </select>
        <button ng-click="update(masjid)">Submit</button>
    </div>
</div>

Working Fiddle