user1828605
user1828605

Reputation: 1735

How to pass value from a model in controller to other child controllers in angularjs?

I'm using AngularJS-UI Datepicker. Here's the HTML:

<div class="form-inline date-picker" ng-show="is('home')">
            <div class="form-inline input-group">
                <input type="month" class="form-control" uib-datepicker-popup ng-model="selectedDate" is-open="status.opened" min-date="reportDate.minDate" max-date="reportDate.maxDate" close-text="Close" /><p>{{ dt }}</p>

                <span class="input-group-btn">
                    <button type="button" class="btn btn-default" ng-click="open($event)"><i class="glyphicon glyphicon-calendar"></i></button>
                </span>               
            </div>
        </div> 

And my controller:

var mainController = monthlyReportApp.controller('MainController', ['$scope', 'ReportDateService', '$state', function ($scope, ReportDateService, $state) {

    $scope.is = function (name) {
        return $state.is(name);
    }

    $scope.selectedDate = new Date();


    $scope.reportDate = [];
    $scope.currentMonth = 0;

    loadRemoteData();

    function loadRemoteData() {
        ReportDateService.list().then(function (response) {
            $scope.reportDate = response;
        });

    }

    $scope.getMonth = function () {

       console.log(angular.isDefined($scope.selectedDate) ? $scope.selectedDate.getMonth() : "nothing");
    }

    $scope.clear = function () {
        $scope.selectedDate = null;
    };

    $scope.open = function($event) {
        $scope.status.opened = true;
    };

    $scope.status = {
        opened: false
    };

    $scope.$watch($scope.selectedDate, function (newVal, oldVal) {
        console.log($scope.selectedDate.toDateString());
    })

}]);

The datepicker shows up just fine, and the input shows the month and year selected.

What I need to do now is the selected month and year should be passed on to other child controllers - there are many. But for some reason, I couldn't even make the selected month and year appear in the parent controller shown above. What am I doing wrong?

When I output the model like {{ selectedDate }} right below the datepicker, the value shows up.

Upvotes: 1

Views: 809

Answers (1)

icfantv
icfantv

Reputation: 4643

First off, don't ever use $rootScope for stuff like that.

Second, the problem is you're storing the date on your controller's scope and not in an object. You need to learn how scopes inherit in Angular. More specifically, you're running into this issue.

Quick and dirty solution is to do $scope.data = {}; data.date = new Date() and then change ng-model="selectedDate" to ng-model="data.date" and your object will inherit correctly.

Upvotes: 1

Related Questions