我有一个很奇怪的问题。由于某种原因,我的 ng-model 仅当我嵌套相同的 Controller 两次时才会绑定(bind)。这是我的代码:
索引页:
bbmean_app.controller('mainController', function($scope, $location, mainFactory){
$scope.test='hello';
$scope.currentUser = {};
$scope.login = function(){
console.log($scope.name)
}
<body>
<div ng-controller='mainController'>
<div ng-view =""></div>
</div>
</body>
查看页面:
<form>
{{test}}
<p>Your name:<input type = 'text' ng-model='name' ></p>
<button type = 'submit' ng-click ='login()'>Login</button>
</form>
所以我的所有 View 都应该有一个 mainController 作为 Controller ,它在 View 页面上显示“hello”,这意味着它可以显示测试(这意味着与 Controller 的连接),但是当我单击提交按钮时,控制台日志未定义。仅当我的 Controller 像这样被调用时它才有效:
<div ng-controller = 'mainController'>
<form>
{{test}}
<p>Your name:<input type = 'text' ng-model='name' ></p>
<button type = 'submit' ng-click ='login()'>Login</button>
</form>
</div>
我的 html 周围有 ng-app,代码中也有正确的 head 标签。 有什么想法吗?
最佳答案
我认为这就是解决这个问题的方法,
.when('/', {
templateUrl: 'js/views/index.html',
replace: true,
controller: 'mainController',
})
通过在路由中声明 Controller ,您可以使用以下方式访问 $scope.name
:
$scope.login = function() {
var name = $scope.name;
console.log(name);
};
无需在 View 中引导/嵌套 mainController
。
关于javascript - ng-model 仅在我嵌套相同的 Controller 时才有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32030944/