我已将所有必要的文件放入一个文件中。我想在用户点击按钮时将项目推送到数组中。以下是内容:
当我点击按钮时,没有任何反应。此外,数据不会重复/循环,{{}}
以角度显示,这意味着存在问题。
<script type="text/javascript" src="angular.js" ></script>
<div data-ng-app="App">
<div data-ng-controller="MyController">
<ul data-ng-repeat="one in names">
<li>{{ one.first }}</li>
</ul>
</div>
</div>
<input type="text" data-ng-model="Namer.name"/>
<input type="submit" data-ng-click="AddName()"/>
<script type="text/javascript">
var App = angular.module("App", []);
App.controller("MyController", function($scope){
$scope.names = [
{ first : "Thomas"},
{ first : "Geferson"},
{ first : "Jenny"},
{ first : "Maria"},
];
$scope.AddName = function(){
$scope.names.push({
name : $scope.Namer.name;
});
};
});
</script>
答案 0 :(得分:8)
<强> Working DEMO 强>
var App = angular.module("App", []);
App.controller("MyController", function ($scope) {
$scope.names = [{
first: "Thomas"
}, {
first: "Geferson"
}, {
first: "Jenny"
}, {
first: "Maria"
}];
$scope.AddName = function () {
$scope.names.push({
first: $scope.Namer.name
});
};
});
你需要移动你的data-ng-click
内部Controller.Also你有一些语法问题。这也是我修复(与IE一起工作)
<div data-ng-app="App">
<div data-ng-controller="MyController">
<ul data-ng-repeat="one in names">
<li>{{ one.first }}</li>
</ul>
<input type="text" data-ng-model="Namer.name" />
<input type="submit" data-ng-click="AddName()" />
</div>
</div>
答案 1 :(得分:3)
将您的输入移至MyController
内部,以便它在控制器创建的范围内执行代码:
<div data-ng-app="App">
<div data-ng-controller="MyController">
<ul data-ng-repeat="one in names">
<li>{{ one.first }}</li>
</ul>
<input type="text" data-ng-model="Namer.name"/>
<input type="submit" data-ng-click="AddName()"/>
</div>
</div>
另一个错误是您需要将name
更改为first
以与现有对象匹配
$scope.AddName = function(){
$scope.names.push({
first : $scope.Namer.name //change to first and remove the ;
});
};