问题
Here is the code snippet about an Angular Controller. I'm trying to learn Angular from this github project
The questionable part is located in function addStock. I have already defined $scope.watchlist in the initilizations part, however, if I remove the re-declaration inside $scope.addStock function, $scope.watchlist will not be populated with right values. Can any Angular experts point me out? If you want to see my full project code - here is the link.
angular.module('stockCatApp')
.controller('WatchlistCtrl', function ($scope, $routeParams, $modal, WatchlistService, CompanyService) {
// Initializations
$scope.companies = CompanyService.query();
$scope.watchlist = WatchlistService.query($routeParams.listId);
$scope.stocks = $scope.watchlist.stocks;
$scope.newStock = {};
var addStockModal = $modal({
scope: $scope,
template: 'views/templates/addstock-modal.html',
show: false
});
$scope.showStockModal = function () {
addStockModal.$promise.then(addStockModal.show);
};
$scope.addStock = function () {
//The following line needs to be put here again in order to retrieve the right value
$scope.watchlist = WatchlistService.query($routeParams.listId);
///////////////////////////////////////////////////////////////////////
$scope.watchlist.addStock({
listId: $routeParams.listId,
company: $scope.newStock.company,
shares: $scope.newStock.shares
});
addStockModal.hide();
$scope.newStock = {};
};
});
回答1:
Can you do a console.log($scope.watchlist); after both of your $scope binds to see if the data and its type match?
$scope.watchlist = WatchlistService.query($routeParams.listId);
console.log($scope.watchlist);
$scope.watchlist.addStock({
listId: $routeParams.listId,
company: $scope.newStock.company,
shares: $scope.newStock.shares
});
console.log($scope.watchlist);
Feel free to post the logs.
回答2:
It appears as if you are calling $scope.addStock() from a modal. In which case the modal does not necessarily inherit the parent scope. It depends on which versions of everything you are using. It looks like you are using angular-strap (I looked in your bower.json). If you look in their $modal source code you will find this:
https://github.com/mgcrea/angular-strap/blob/master/src/modal/modal.js
var scope = $modal.$scope = options.scope && options.scope.$new() || $rootScope.$new();
So, when you are opening your modal you are creating a new scope. You might be able to access the original scope using $parent though.
来源:https://stackoverflow.com/questions/32914936/the-scope-variable-is-undefined-unless-i-forced-it-to-retrieve-from-service-aga