Search code examples
javascripthtmlangularjsangularjs-scopeangularjs-watch

Angular $watch command selecting undefined variable


I have some HTML code in which I use angular to repeat radio inputs.

I created a plunkr showing the functionality that I have right now.

http://plnkr.co/edit/n5OZVlbiwToHsuvGN3QI

The repeating code binds to a variable which I need to capture into the top level scope. ($parent.selectedType and $parent.selectedSpecies)

The code displays correctly in the HTML document but the data binding from ng-model does not work.

Thus I've set up a $scope.$watch command like this:

  $scope.$watch('type.selected', function (newVal, oldVal) {
        $scope.type.selected.forEach(function (typeName) {
            if (typeName === newVal) {
                $scope.selectedType = $scope.type.selected;
            }
        });
    });

to watch for changes in the typeName variable and when it changes set $scope.selectedType to what I just selected in the radio buttons.

However, when I try to run this code I keep getting "type is undefined" even though the $scope.$watch part is immedately after type definition.

Why is type undefined when I try to $watch it?

edit: The issue was deeper - it comes from the fact that $scope.type.selected.forEach() is not a function that is recognized. forEach() should be a function though, am I missing something?


Solution

  • You have a bunch of logic errors, here it is cleaned up:

    $scope.$watch('type.selected', function (newVal, oldVal, $scope) {
        if ($scope.type.selected) {
            angular.forEach($scope.type.selected, function (value, typeName) {
                if (typeName === newVal) {
                    $scope.selectedType = $scope.type.selected;
                }
            });
        }
    });
    

    As you can see there is a function being passed into the forEach. I believe this is where your issue is. Also I don't think the 3rd parameter of a $watch is $scope.