Angularjs:绑定在UI路由嵌套的状态不工作 [英] Angularjs: Binding in ui-routing nested state not working
问题描述
我有这些的状态在我的应用程序的配置:
I have a these states in my app config:
...
.state('register', {
templateUrl: 'views/register/register.html',
controller: "registerCtrl"
})
.state('register.step-one', {
url: "/register.one",
templateUrl: "views/register/register.one.html",
controller: "registerOneCtrl"
})
.state('register.step-two', {
url: "/register.two",
templateUrl: "views/register/register.two.html",
controller: "registerTwoCtrl"
})
我的主控制器是这样的 registerCtrl
$scope.studies = [];
$scope.newStudy = "dd";
$scope.addStudy = function (studyName) {
$scope.studies.push({
title: studyName
});
console.log($scope.newStudy); //This prints empty
$scope.newStudy = "AAAAA"; //this doesn't seem to work :(
console.log($scope.newStudy);
}
和我有这个在我的 register.two 模板:
And I have this in my register.two template:
<div class="container-fluid margin-top-md">
<input type="text" ng-model="newStudy"/>
<i class="fa fa fa-plus-square" ng-click="addStudy(newStudy)"></i>
<ul>
<li ng-repeat="study in studies">
<input type="text" ng-model="study.title"/>
</li>
</ul>
</div>
现在,这是行不通的罚款研究添加,因为之后,我想更新我的newStudy输入字段,但是,我不能这样做,因为该变量似乎并没有影响到我的模板。
Now, this is not working fine because after a study is added, I would like to update my newStudy input field, however, I'm unable to do so, because that variable doesn't seem to affect my template.
如果我把我的控制器code里面registerTwoCtrl,然后正常工作。我如何使用一个控制器(父控制器),使这项工作?
If I place my controller code inside registerTwoCtrl, then it works fine. How can I make this work using a single controller (The parent controller)?
谢谢!
推荐答案
这是没有使用拇指的NG-模型黄金规则的经典案例:
This is a classic case of failing to use the ng-model Golden Rule of Thumb:
总是有一个。在NG-模型前pression
Always have a "." in your ng-model expression
如果您存储 newStudy
作为一个在 $范围
一个对象的属性 registerCtrl
,它会正常工作。
If you store the newStudy
as a property of an object on the $scope
in registerCtrl
, it will work fine.
例如。
在registerCtrl:
In registerCtrl:
$scope.data = { newStudy: "AAAA" }; // instead of $scope.newStudy = "AAAA";
在模板中,将其更改为:
In the template, change it to:
<div class="container-fluid margin-top-md">
<input type="text" ng-model="data.newStudy"/>
<i class="fa fa fa-plus-square" ng-click="addStudy(data.newStudy)"></i>
<ul>
<li ng-repeat="study in studies">
<input type="text" ng-model="study.title"/>
</li>
</ul>
</div>
一个可能是更好的选择是使用控制器
语法。你看它,它会帮助消除这些类型的错误,因为你将被参考<code> registerCtrl.newStudy 而不仅仅是 newStudy $ C $的C>在NG-模型前pression。
A possibly better alternative is to use the controller as
syntax. Look it up, it will help eliminate these kinds of errors because you will then be referring to registerCtrl.newStudy
instead of just newStudy
in your ng-model expression.
这篇关于Angularjs:绑定在UI路由嵌套的状态不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!