我在使用ng-init
时遇到了问题,并在我的html中分配了模型。
以下代码正常。以下代码用于添加/编辑功能。例如,当行在Edit
模式下打开时,它会保留现有值,并在textbox
中显示。
<div>
<div ng-if="title == 'Add Student'">
<input type="text" name="name"placeholder="Student Name" data-ng-model="registration.Student.FirstName" maxlength="50">
</div>
<div ng-if="title == 'Edit Student'">
<input type="text" name="name"placeholder="Student Name" data-ng-model="student.Student.FirstName" maxlength="50">
</div>
</div>
但是,以下代码是上述代码的简短版本不起作用。我的意思是当行在编辑模式下打开时,它显示文本字段但不显示其中的现有值(名字)。 为什么?
<div ng-init="model = (title == 'Add Student' ? registration.Student : student.Student)">
<input type="text" name="name" placeholder="Student Name" data-ng-model="model.FirstName" maxlength="50">
</div>
请建议是否不能以这种方式使用ng-init或在我的代码中使用某些问题?
感谢
控制器
var currentState = $state.current.name;
if if (currentState == "Add")
{
$scope.registration = {
Student: {
FirstName: '',
}
var _init = function () {
}
$scope.title = " Add Student";
}
else
{
$scope.student= {};
$scope.student= response[0];
var _init = function () {
$scope.title = " Edit Student";
}
}
答案 0 :(得分:2)
当ng-init
阻止错误时,它正在返回true
或false
,你正在弄乱括号。
<强>标记强>
<div ng-init="model = (title == 'Add Student') ? registration.Student : student.Student">
<input type="text" name="name" placeholder="Student Name" data-ng-model="model.FirstName" maxlength="50">
</div>
<强>更新强>
在您目前的情况下,当{DOMO}在DOM上呈现元素时,ng-init
正在执行,registration.Student
&amp; student.Student
没有任何价值。评估将ng-init
设置为model
学生的空对象。我建议你从控制器逻辑中设置更安全的模型值。
<强>代码强>
var currentState = $state.current.name;
if (currentState == "Add")
{
$scope.registration = {
Student: {
FirstName: '',
}
var _init = function () {
}
$scope.title = " Add Student";
}
else
{
$scope.student= {};
$scope.student= response[0];
var _init = function () {
$scope.title = " Edit Student";
}
//shifted logic in controller
$scope.model = (title == 'Add Student' ? registration.Student : student.Student);
}
<强>标记强>
<div>
<input type="text" name="name" placeholder="Student Name"
data-ng-model="model.FirstName" maxlength="50"/>
</div>
其他方式你可以添加一个像loadedData
这样的标志,它会说已经获取了ajax响应&amp; registration.Student
&amp;范围内提供了student.Student
个值。
<强>标记强>
<div ng-if="loadedData">
<input type="text" name="name" placeholder="Student Name" data-ng-model="model.FirstName" maxlength="50">
</div>
<强>代码强>
var currentState = $state.current.name;
if (currentState == "Add")
{
$scope.registration = {
Student: {
FirstName: '',
}
var _init = function () {
}
$scope.title = " Add Student";
}
else
{
$scope.student= {};
$scope.student= response[0];
var _init = function () {
$scope.title = " Edit Student";
}
//set flag
$scope.loadedData = true;
}