I am facing one weird scenario while using angularJS. [new to AngularJS]
I am calling one function from my index.html which is defined in controller.js.
<li><a ng-click="casualShirts()" data-ng-controller="MyCtrl2" href="#/view2">Casual Shirts</a></li>
/#View2 is my partial2.html.
In Controller the code is:
app.controller('MyCtrl2', ['$scope', '$location', 'UserFactory', '$q', function ($scope, $location, UserFactory, $q) {
//$scope.home = UserFactory.home.query();
$scope.casualShirts = function () {
console.log("casualshirts");
$scope.home = UserFactory.casualshirts.query({key: 'Casual Shirts'}, function (home) {
console.log('(callback) read more ' + $scope.home.length); // <= will log correct length
});
console.log('read more ' + $scope.home.length); // <= will always log 0
$scope.$watch('home.length', function (length) {
if (length) { // <= first time length is changed from undefined to 0
console.log('(watch) read more ' + $scope.home.length); // <= will log correct length
}
});
console.log("casualshirts length - " + $scope.home.length);
var deferred = $q.defer();
var promise = deferred.promise;
promise.then(function (result) {
alert('success - ' + result);
}, function (reason) {
alert('Error - ' + reason);
});
$location.path('/view2');
}
}]);
The data is returned properly from service and I can see them in console.log when watch is applied. logs are:
casualshirts controllers.js:29
read more 0 controllers.js:34
casualshirts length - 0 controllers.js:41
(callback) read more 527 controllers.js:31
(watch) read more 527
But the same data is not coming to UI and its not visible.
Weird part is: If same
$scope.home = UserFactory.home.query();
Services.js - EDIT
var services = angular.module('ngdemo.services', ['ngResource']);
services.factory('UserFactory', ['$resource', '$rootScope', function ($resource, $rootScope) {
/*alert("I am here service");*/
console.log("casualshirts service");
return {
casualshirts: $resource('/rest/users/:key', {}, {
query: {method: 'GET', isArray: true , params: {key : '@key'} },
create: {method: 'POST'}
}),
allresults: $resource('/rest/users/cats', {}, {
query: {method: 'GET', params: {}, isArray: true }
// create: {method: 'POST'}
})};
}]);
is called without being inside any $scope.casualShirts function, data is coming to UI.
Am I missing anything here? Please suggest.
Thanks in advance