简体   繁体   中英

Why is the object I add to my ngModel in angular showing up as undefined when passed through console.log?

I have two directives in my angular app.

Directive 1 has an ngModel that is an array of objects. Through the directive methods, I am pushing an object to the end of the array.

So for example, the original ngModel array is [1,2,3,4], and I am adding, 5 so the array looks like [1,2,3,4,5].

This ngModel gets passed as the ngModel to my second directive. I can console.log the array and see all 5 items, but when I try to access the last item, the item that I added, it does not show up. For example, if I do a foreach on the array, it's like the last item doesn't exist.

I cannot access the item. Anyone have any ideas why?

Thanks!

I suppose you use the link function to add the fifth item in your parent directive.

There are two types of link functions: pre and post link. Let's say you have parent and nested child directive. The link functions are going to be called in this order:

  • parent pre-link
  • child pre-link
  • child post-link
  • parent post-link

By default if you use link in you directive object notation, it will be the post-link function.

return {
   link: function (scope, element, attrs) { }
}

And if you add your fifth element in the parent post-link, then it will not be available for the child, as it will be added after the child link has been called. The way to give properly initialized data to the child is either to use pre-link or controller (but the latter is out of scope here).

return {
    link: {
        pre: function (scope, element, attrs) { }
    }
}

Here is a working plnkr with your example: http://plnkr.co/edit/24KrGLdnkDCrLr2SzXhQ?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM