问题描述
在此question,我面临的另一个挑战,在$范围内的型号和功能似乎已经停止工作。下面是测试code,在添加按钮似乎并没有收集任何数据I输入<输入类型='文本'NG-模式='newPerson'/ >
了,
After this question, I am facing another challenge, the model and function inside the $scope seem have stopped working. Below is the test code, the Add button seem does not collect any data I input from <input type='text' ng-model='newPerson' />
anymore,
HTML
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>AngularJS</title>
<meta charset="utf-8">
<script src="js/jquery-1.10.1.min.js"></script>
<script src="js/angular.min.js"></script>
<script src="js/app.js" type="text/javascript"></script>
</head>
<body>
<div ng-app='MyTutorialApp' ng-controller='MainController'>
<div ng-include='thisIsAScopeProperty'></div>
</div>
</body>
</html>
外部模板,
<div id='content'>
<input type='text' ng-model='searchText' />
<ul>
<li ng-repeat='person in people | filter:searchText' ng-show='person.live == true'>#{{person.id}} {{person.name}}</li>
</ul>
<input type='text' ng-model='newPerson' />
<button ng-click='addNew()'>Add</button>
</div>
angularjs,
angularjs,
var app = angular.module('MyTutorialApp',[]);
app.controller("MainController", function($scope){
$scope.thisIsAScopeProperty = 'template/index.html';
$scope.people = [
{
id: 0,
name: 'Leon',
music: [
'Rock',
'Metal',
'Dubstep',
'Electro'
],
live: true
}
];
$scope.newPerson = null;
$scope.addNew = function() {
alert(1); // works here when you click the Add button
console.log($scope.newPerson); // but returns nothing when you type any text in the input
if ($scope.newPerson != null && $scope.newPerson != "") {
alert(2); // does not work here
$scope.people.push({
id: $scope.people.length,
name: $scope.newPerson,
live: true,
music: [
'Pop',
'RnB',
'Hip Hop'
]
});
}
}
});
任何想法,为什么,我该如何解决这个问题?
Any ideas why and how can I fix it?
推荐答案
使用
<input type='text' ng-model='$parent.newPerson' />
NG-包括
创建一个新的范围,因为newPerson是一个简单的属性,这是对孩子和家长作用域一个不同的(即改变一个没有变化另一个)。因此,当包括模板集 newPerson
它仍然在mainController的范围为null。
ng-include
creates a new scope, and because newPerson is a simple property, it's a different one on the child and parent scopes (i.e. changing one doesn't change the other). So when the included template sets newPerson
it's still null on the mainController's scope.
为了更好地理解如何作用域的工作,阅读
For a better understanding of how scopes work, read https://github.com/angular/angular.js/wiki/Understanding-Scopes
这篇关于Angularjs模板:模型和功能停止外部模板的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!