Reputation: 47
I have two functions calls in Angular the first one is called in the ng-init
event using this:
ng-init="dateCall()"
And the function is:
$scope.dateCall = function() {
var date, endDate;
$scope.start_date = $filter('date')(new Date(), 'MM/dd/yyyy');
date = new Date($scope.start_date);
$scope.season = $scope.fundraiser_seasons.find(function(e) {
return Date.create(e.start_date) <= date && date <= Date.create(e.end_date);
});
endDate = $filter('date')(new Date($scope.season.end_date), 'MM/dd/yyyy');
return $scope.end_date = endDate;
};
Which for some reason will not return a value for $scope.season
. However this almost identical event works completely fine whenever I change the value for $scope.start_date.
$scope.$watch("start_date", function(start_date) {
var date, endDate;
if ($scope.fundraiser_seasons.length === 0) {
return;
}
date = new Date(start_date);
$scope.season = $scope.fundraiser_seasons.find(function(e) {
return Date.create(e.start_date) <= date && date <= Date.create(e.end_date);
});
endDate = $filter('date')(new Date($scope.season.end_date), 'MM/dd/yyyy');
return $scope.end_date = endDate;
});
I've been troubleshooting this forever and can not get it to work and feel like I must be missing something stupid. Basically I just want it to return that end_date
based on todays day when the app loads - and I know the return of that value works fine in the $watch
function. Thanks in advance.
Upvotes: 0
Views: 95
Reputation: 16811
Most likely you have an empty array in $scope.fundraiser_seasons
when it's used in the NgInit event.
Instead of storing the same logic in two seperate function refactor the code to use the same logic like this
$scope.dateCall = function() {
$scope.start_date = $filter('date')(new Date(), 'MM/dd/yyyy');
var date = new Date($scope.start_date);
calcDate(date);
};
$scope.$watch("start_date", function(start_date) {
var date = new Date(start_date);
calcDate(date);
});
var calcDate = function(date){
if ($scope.fundraiser_seasons.length === 0) {
return;
}
$scope.season = $scope.fundraiser_seasons.find(function(e) {
return Date.create(e.start_date) <= date && date <= Date.create(e.end_date);
});
var endDate = $filter('date')(new Date($scope.season.end_date), 'MM/dd/yyyy');
return $scope.end_date = endDate;
};
Upvotes: 1
Reputation: 869
if you want to use the return value from the ng-init, you can assign it
ng-init="result=dateCall()"
I'm not sure what you mean by the return value from the $watch. return to who? its meaningless.
Upvotes: 0