Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: input not binding to expected scope when inside a view

I'm having an issue with binding an input from inside a view. I thought it would bind to the controller scope, but it seems to be binding to a child scope, so it's not updating above.

Other items will bind like I expect if they're inside an ng-repeat (I'm not sure why).

Here's an example:
http://jsfiddle.net/hMpsB/1/

What's the best way to bind the input to the correct scope if it's not inside an ng-repeat?

like image 872
valan Avatar asked Oct 08 '12 21:10

valan


1 Answers

In your example you will have better luck binding your $scope.test to an object instead of a primitive type like this:

$scope.test = { val: "test value" };

You can see this fiddle for a working example.

The child scope that gets created in the ngView will copy your value and since your original $scope.test is a primitive string it has no link to the parent value so your input will be modifying the child scope copy. When binding to an object your child scope has a copy of the object reference but will ultimately modify the same instance of the object.

You can take a look at this question for more information on creating a service to persist data across multiple controllers (which is a little similar to your question).

You can also look into using $parent as described in this answer though as Mark mentions it's undocumented and might get messy if another child scope ever gets introduced somewhere.

like image 109
Gloopy Avatar answered Nov 08 '22 01:11

Gloopy