我想设置ng-model Value。我尝试使用ng-init和value tag。
我的代码:
初始化
{{formObject.consultantId}} // value prints
<input type="hidden" data-ng-model="formObject.consultant.id" data-ng-init="formObject.consultant.id=formObject.consultantId">
{{formObject.consultant.id}} // no data Prints
值
{{formObject.consultantId}} // value prints
<input type="hidden" data-ng-model="formObject.consultant.id" value="{{formObject.consultantId}}">
{{formObject.consultant.id}} // no data Prints
这对我有用
<input type="hidden" data-ng-model="formObject.consultant.id" data-ng-init="formObject.consultant.id='test'">
{{formObject.consultant.id}} // prints as test
我的代码有什么问题?如何将此值初始化为模型?
修改
我发现了我的问题。此代码适用于普通Html表单。 但是上面的代码在ModelForm(指令)中。
答案 0 :(得分:1)
您应该将{{formObject.consultantShare.consultant.id}}
更改为{{formObject.consultant.id}}
( to OP's edit, now removed )
看看这个
var app = angular.module('myApp', []);
app.controller('Controller', function ($scope) {
$scope.formObject = {};
$scope.formObject.consultant = {};
$scope.formObject.consultantId = "254";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myApp' ng-controller="Controller">{{formObject.consultantId}} // value prints
<input type="hidden" data-ng-model="formObject.consultant.id" data-ng-init="formObject.consultant.id=formObject.consultantId" />{{formObject.consultant.id}}
<br/>{{formObject.consultantId}} // value prints
<input type="hidden" data-ng-model="formObject.consultant.id" value="{{formObject.consultantId}}"/>{{formObject.consultant.id}}
</div>
答案 1 :(得分:0)
您可以共享控制器以查看formObject的初始化方式。与此同时我添加了
var myapp= angular.module('myForm',[]);
(function(){
angular.module('myForm').controller('formController',[formController]);
function formController(){
var vm = this;
vm.formObject = {consultantId:10,consultant:{consultantId:''}};
}
})();
&#13;
<!DOCTYPE html>
<html ng-app="myForm">
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div ng-controller="formController as vm">
<span>formObject.consultantId:{{vm.formObject.consultantId}}</span>
<input type="hidden" ng-model="vm.formObject.consultantId" ng-init="vm.formObject.consultant.consultantId=vm.formObject.consultantId"
</br>
<span>formObject.consultant.consultantId: {{vm.formObject.consultant.consultantId}}</span>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="formController.js"></script>
</body>
</html>
&#13;