1

What is wrong with this code? I expect to see the value of 1 being printed in the console but instead it throws an error stating that self.list[0] is undefined???

<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.js">
</script>
<script type="text/javascript">
    angular.module('notesApp', [])
        .controller('MainCtrl', ['ItemService', function(ItemService) {
            var self = this;
            self.list = function() {
                return ItemService.list();
            };

            console.log(self.list[0].id); //<<-- why does it print undefined??

            self.add = function() {
                ItemService.add({
                    id: self.list().length + 1,
                    label: 'Item ' + self.list().length
                });
            };

        }])
        .factory('ItemService', [function() {
            var items = [
                {id: 1, label: 'Item 0'},
                {id: 2, label: 'Item 1'}
            ];
            return {
                list: function() {
                    return items;
                },
                add: function(item) {
                    items.push(item);
                }
            };



        }]);    

Thank you in advance to anyone who answers. Also, was trying not to be so blunt but SO won't allow me to put a simple greeting at the start of the question...

1 Answer 1

1

Because at this point self.list is a function!! When the following is executed,

self.list = function() {
   return ItemService.list();
};

As you are expecting a list there, maybe you need to execute the function -- something like

self.list = function() {
   return ItemService.list();
}();

Try simply!

console.log("see self.list=", self.list);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.