Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare Object within $scope AngularJS

I'm using AngularJS and I'm trying to create a template where I have an implicit object that calls test and inside test I have an array that I want to repeat when I call a function inside my Controller, but I'm getting undefined error when I'm trying do push an object inside the array.

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?

like image 626
Lucas Avatar asked Feb 04 '15 13:02

Lucas


1 Answers

You are going to want to do something like this:

Example can be seen here - http://jsfiddle.net/hm53pyjp/4/

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 person object that you can add things to and create a function to push objects to it. So here I have created a person with the properties name and phones. I have give the name property a value of "User" and the phones property an array of numbers. In this case I have just populated one number to get started.

The function then gets called on the ng-click and simply pushes an object to the existing phones array.

As you push the objects to the array the ng-repeat will start to update the inputs on the page.

function TestCtrl($scope) {
    $scope.person = {
        name : "User",
        phones : [{number: 12345}]
    };

    $scope.createPhone = function () {

        $scope.person.phones.push({
            'number' : '111-222'
        });

    };
}
like image 197
haxtbh Avatar answered Nov 15 '22 20:11

haxtbh