使用angularJS时,我面临一个奇怪的场景。 [AngularJS新手]
我正在调用我的index.html中的一个函数,该函数在controller.js中定义。
<li><a ng-click="casualShirts()" data-ng-controller="MyCtrl2" href="#/view2">Casual Shirts</a></li>
/#View2是我的partial2.html。
在Controller中代码为:
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');
}
}]);
数据从服务中正确返回,我可以在应用监视时在console.log中看到它们。日志是:
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
但是相同的数据并没有进入用户界面并且不可见。
奇怪的部分是:如果相同
$scope.home = UserFactory.home.query();
Services.js - 编辑
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'}
})};
}]);
在没有任何$ scope.casualShirts函数的情况下被调用,数据将进入UI。
我在这里遗漏了什么?请建议。
提前致谢