I have a basic app with a state setup, such as:
.....config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('tab.dash', {
url: '/dash',
views: {
'tab-dash': {
templateUrl: 'templates/tab-dash.html',
controller: 'SearchCtrl as search'
}
}
});
.....
$urlRouterProvider.otherwise('/tab/dash');
Then in tab-dash template I have the following:
<select class="item item-input" ng-model="formData.category" ng-options="category as category.name for category in search.categories track by category.id">
And the SearchCtrl has the following $watch:
.controller('SearchCtrl', function($scope, service) {
$scope.$watch('formData.category', function(cat){
console.log("here");
Yes, these are just extracts of each file for brevity sake. The code structure is based on one of the ionic samples.
The console logs "here" on the initial page view, but once I make a selection change on "formData.category" there are no more console logs. When I had the exact same code, in a simple 1 html page (non ionic) angular app I didn't have this issue. The $watch would detect any changes, but not now.
This is really doing my head in.
Any ideas?
Thanks
Can you try the below?
$scope.$watch('formData.category', function (newVal, oldVal) { console.log("here"); }, true);
Please note third parameter (true).
From documentation, objectEquality (optional) Compare for object equality using angular.equals instead of comparing for reference equality.
If the above trick does not work, you can try the below too.
$scope.$watch(function ( $scope ) {
return $scope.formData.category;
}, function(newVal, oldVal){
if(newVal != oldVal) {
console.log('here');
}
});
Can you please try ng-change
<select class="item item-input" ng-model="formData.category" ng-options="category as category.name for category in search.categories track by category.id" ng-change="valueChanged()">
$scope.valueChanged = function(){
// you can do what you are doing in $watch
console.log("here");
}
I worked out the answer with some good old fashion head banging, I added the following line to the top of the 'SearchCtrl' controller:
$scope.formData = {};
//...also $scope.formData = []; works too
I'm unsure why this object (or array) declaration wasn't necessary on my single html page, single controller regular angular js app, but seems to be necessary here.
Any explanation would be gretly appreciated.