AngularJS 表單中,`` 同時擁有 `value` 屬性 (伺服器端渲染/直寫) 與 `ng-model` 綁定時,初始值無法正確同步到 `$scope` 模型,導致提交資料為空或舊值。
<!-- 問題示範 -->
<input type="text" name="name" ng-model="formData.name" value="張三">
{{ formData.name }} <!-- 顯示空白或 undefined -->
AngularJS 編譯階段會建立 `` 的 `NgModelController`,並以 **JavaScript 端模型 (`$scope.formData.name`) 為單一真實來源**。`value` 屬性僅在初始渲染時由瀏覽器設定 DOM 屬性,Angular **不會自動從 DOM 讀取 value 同步到模型**。
<div ng-controller="FormController">
<form name="myForm" ng-submit="submit()">
<input type="text" name="name" ng-model="formData.name" placeholder="姓名">
<input type="text" name="remark" ng-model="formData.remark" placeholder="備註">
<button type="submit">送出</button>
</form>
</div>
<script>
angular.module('formApp', [])
.controller('FormController', ['$scope', '$http', function($scope, $http) {
// 1. 直接在 Controller 宣告初始值 (可來自後端模板注入 JSON)
$scope.formData = {
name: '張三', // 後端渲染時: name:
remark: '預設備註'
};
$scope.submit = function() {
$http({
method: 'POST',
url: '/api/user/update',
data: $.param($scope.formData), // jQuery 序列化為 application/x-www-form-urlencoded
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function(resp) {
alert('儲存成功');
}, function(err) {
alert('儲存失敗: ' + err.data.message);
});
};
}]);
<div ng-app="formApp" ng-init="formData = { name: '張三', remark: '備註' }">
<input type="text" name="name" ng-model="formData.name">
<input type="text" name="remark" ng-model="formData.remark">
<button ng-click="submit()">送出</button>
</div>
<script>
angular.module('formApp', [])
.controller('FormController', ['$scope', '$http', function($scope, $http) {
$scope.submit = function() {
// $scope.formData 已有值
$http.post('/api/user/update', $scope.formData).then(...);
};
}]);
> ⚠️ **官方不推薦** 大量使用 `ng-init`,僅適用於極簡單的原型或靜態初始化。複雜邏輯請用 Controller/Service。
angular.module('formApp').directive('initNgModel', function($parse) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
// 取得 value 屬性值
const val = attrs.value;
if (val !== undefined) {
// 設定模型值 (觸發 $parsers/$formatters)
ngModelCtrl.$setViewValue(val);
ngModelCtrl.$render();
// 同步到 scope 物件
$parse(attrs.ngModel).assign(scope, val);
}
}
};
});
// 使用
<input type="text" ng-model="formData.name" value="張三" init-ng-model>
// 需引入 jQuery 或手寫序列化
data: $.param($scope.formData)
// 純 Angular (需注入 $httpParamSerializer)
data: $httpParamSerializer($scope.formData)
// headers 同樣設定 application/x-www-form-urlencoded
$http({
method: 'POST',
url: '/api/user/update',
data: $scope.formData, // 直接傳物件,Angular 自動 JSON.stringify
headers: { 'Content-Type': 'application/json' }
});
<form name="myForm" novalidate ng-submit="submit()">
<input name="name" ng-model="formData.name" required ng-minlength="2">
<span ng-show="myForm.name.$error.required">必填</span>
<span ng-show="myForm.name.$error.minlength">至少 2 字</span>
<button type="submit" ng-disabled="myForm.$invalid">送出</button>
</form>
| AngularJS | Angular (v2+) | Vue 3 | React |
|---|---|---|---|
| `ng-model` 雙向綁定 | `[(ngModel)]` (FormsModule) / Reactive Forms | `v-model` | `value` + `onChange` (受控元件) |
| Controller `$scope` | Component Class / Signals | `setup()` + `ref`/`reactive` | Function Component + `useState` |
| `$http` | `HttpClient` (Observable) | `fetch` / `axios` / `useFetch` | `fetch` / `axios` / `react-query` |
| `ng-init` | Component `constructor`/`ngOnInit` | `onMounted` / `ref` 初始化 | `useEffect` 初始化 |