Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my $watch only ever fire once?

I'm factoring out some widget and the $watch expression works perfectly having all in one file but now I moved the relevant controller part into a new controller and the markup into a new html and the $watch fires exactly once after initialization but not when editing typing in the associated input.

JS:

app.controller('getRecipientWidgetController', [ '$scope', function($scope) {
    console.log("controller initializing")
    var testReceivingAddress = function(input) {
        console.log("change detected")
    }
    $scope.$watch("addressInput", testReceivingAddress)
} ])

HTML of wrapper:

<ng-include
    src="'partials/getRecipientWidget.html'"
    ng-controller="getRecipientWidgetController"
    ng-init="recipient=cert"> <!-- ng-init doesn't influence the bug. -->
</ng-include>

HTML of partials/getRecipientWidget.html:

<md-text-float ng-model="addressInput"></md-text-float>

I suspect there is some scope voodoo going on? I left the ng-init in to make clear what I want to achieve: build an obviously more complex, reusable widget that in this instance would work on $scope.cert as its recipient.

like image 391
Giszmo Avatar asked Mar 17 '15 22:03

Giszmo


2 Answers

That is probably because ng-include will create a new inherited scope on the included HTML, hence $scope.addressInput in your controller is not the same reference as $scope.addressInput in getRecipientWidget.html

Well it's not easy to explain, but you should either put ng-controller within the HTML of getRecipientWidget.html (and not on the div above that includes it), OR you can use an object such as something.addressInput instead of the raw addressInput which avoids references issues on raw types (number/string).

like image 143
floribon Avatar answered Nov 10 '22 17:11

floribon


ng-include creates new scope.

Try this

<md-text-float ng-model="$parent.addressInput"></md-text-float>

Plunker example

like image 3
kodebot Avatar answered Nov 10 '22 16:11

kodebot