问题描述
这是关于 Angular 控制器的代码片段.我正在尝试从此 github项目
Here is the code snippet about an Angular Controller. I'm trying to learn Angular from this github project
有问题的部分位于函数 addStock 中.我已经在 initilizations 部分定义了 $scope.watchlist,但是,如果我删除 $scope.addStock 函数中的重新声明,$scope.watchlist 将不会填充了正确的值.任何 Angular 专家都可以指出我吗?如果您想查看我的完整项目代码 - 这是 链接.p>
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 = {};
};
});
推荐答案
看起来好像您正在从模式调用 $scope.addStock().在这种情况下,模态不一定继承父范围.这取决于您使用的所有内容的版本.看起来您正在使用 angular-strap(我查看了您的 bower.json).如果你查看他们的 $modal 源代码,你会发现:
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();
var scope = $modal.$scope = options.scope && options.scope.$new() || $rootScope.$new();
因此,当您打开模式时,您正在创建一个新范围.不过,您也许可以使用 $parent 访问原始范围.
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.
这篇关于$scope 变量是未定义的,除非我强制它再次从服务中检索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!