Search code examples
javascriptangularjsangularjs-directiveangularjs-scopepropagation

Angular data propagation through scope tree with controllers


I'm in the process of learning Angular, and have come across a bit of a problem. I'm trying to create a set of directives that represent different levels within a javascript object. The object contains a number of different properties that depend on the state of other parts of the model. For example, if one of the sub properties is in an error state, the parent is also. I have an extremely over-simplified example HERE. Any help would be greatly appreciated. Especially if someone could explain what's going wrong with the example and offer advise on high-level best practices for angular design. Thanks.


Solution

  • The problem with your example has to do with the new scope that is created by ng-repeat. I'll refer you here for a very detailed explanation, but here's the takeaway:

    For each item/iteration, ng-repeat creates a new scope, which prototypically inherits from the parent scope, but it also assigns the item's value to a new property on the new child scope.

    If item is a primitive, essentially a copy of the value is assigned to the new child scope property. Changing the child scope property's value (i.e., using ng-model) does not change the array the parent scope references.

    It's a confusing issue with a simple solution: Make your bindable values objects instead of primitives.

    In your example, replace

    scope.innerValues = [1,2,3];
    

    with

    scope.innerValues = [{value: 1}, {value:2}, {value:3}];
    

    Here's your example modified to work: http://plnkr.co/edit/IXKk75721MHNsI0zeBEG?p=preview