Javascript 如何在 $scope AngularJS 中声明对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28322807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to declare Object within $scope AngularJS
提问by Lucas
I'm using AngularJS and I'm trying to create a template where I have an implicit object that calls testand inside testI have an array that I want to repeat when I call a function inside my Controller, but I'm getting undefined errorwhen I'm trying do push an object inside the array.
我正在使用 AngularJS 并且我正在尝试创建一个模板,其中我有一个调用test的隐式对象和内部测试我有一个数组,当我在我的控制器中调用一个函数时,我想重复这个数组,但是我得到了未定义当我尝试将对象推送到数组中时出错。
Here is the example of my code:
这是我的代码示例:
<body ng-app="MyApp" ng-controller"MyController">
<input ng-model="person.name">
<button ng-click="createPhone()">
<div data-ng-repeat="phone in person.phones">
<input ng-model="phone.number">
</div>
</div>
</div>
Here is my Controller:
这是我的控制器:
//app.controller...
$scope.createPhone(){
var phone = {number: '123456789'};
$scope.person.phones.push(phone);
}
I'm getting:
我越来越:
TypeError: Cannot set property 'phones' of undefined.
类型错误:无法设置未定义的属性“电话”。
Could anyone help me?
有人可以帮助我吗?
回答by haxtbh
You are going to want to do something like this:
你会想要做这样的事情:
Example can be seen here - http://jsfiddle.net/hm53pyjp/4/
示例可以在这里看到 - http://jsfiddle.net/hm53pyjp/4/
HTML:
HTML:
<div ng-app>
<div ng-controller="TestCtrl">
<input ng-model="person.name" />
<button ng-click="createPhone()">Create Phone</button>
<div ng-repeat="phone in person.phones">
<input ng-model="phone.number" />
</div>
</div>
</div>
Controller:
控制器:
Create a personobject that you can add things to and create a function to push objects to it.
So here I have created a personwith the properties nameand phones. I have give the nameproperty a value of "User" and the phonesproperty an array of numbers. In this case I have just populated one number to get started.
创建一个person可以添加东西的对象,并创建一个函数来将对象推送到它。所以在这里我创建了一个person具有属性name和phones. 我给name属性一个值“用户”,phones属性一个数字数组。在这种情况下,我刚刚填充了一个数字以开始使用。
The function then gets called on the ng-clickand simply pushes an object to the existing phonesarray.
然后该函数被调用ng-click并简单地将一个对象推送到现有phones数组。
As you push the objects to the array the ng-repeatwill start to update the inputs on the page.
当您将对象推送到数组时,ng-repeat将开始更新页面上的输入。
function TestCtrl($scope) {
$scope.person = {
name : "User",
phones : [{number: 12345}]
};
$scope.createPhone = function () {
$scope.person.phones.push({
'number' : '111-222'
});
};
}

