angularjs在函数之间共享变量
在控制器中,我想在两个函数之间共享数据。例如:angularjs在函数之间共享变量
controllers.controller('rightDrawerCtrl', function ($scope, $http) {
$scope.shared_id;
$scope.getId = function() {
// get the id via $http, using a secondary id to retrieve the shared_id
}
$scope.useId = function() {
// use the shared_id to make a different api call
}
});
但是在本例中,当调用useId()时,shared_id是未定义的。
我认为这是因为useId是'创建',而shared_id是未定义的,所以没有被通知新的值。
我发现,通过使用两个控制器来解决这个问题的唯一途径:Share data between AngularJS controllers
有没有更好的方式来做到这一点,只使用1个控制器?
貌似我根本就包在$范围变量赋值。$应用
$scope.$apply(function() {
$scope.shared_id = 1234;
});
$scope.shared_id;
上述声明$scope
的shared_id
变量应该是不确定的后 - 因为你没有指定任何价值。
尽管如此,变量仍可在任何示波器功能内访问,因为$scope
对于它们是全局的。不要忘记,你应该在所有地方访问它像$scope.shared_id
。
但是,如果您按以下方式初始化:
$scope.shared_id = 'no id';
..它不会返回undefined。
您也可以通过ng-init
初始化此变量。
虽然这会阻止它返回'未定义' - 我无法访问自从初始化 – SpottedMagpie
创建小提琴以来对变量所做的任何更改。 –
您可以使用像这样用this
要容易得多。
var self = this;
this.shared_id;
$scope.getId = function() {
console.log(self.shared_id) ;
}
$scope.useId = function() {
console.log(self.shared_id) ;
}
如果您必须使用此方法,请在shared_id周围添加一个超时以首先启动它。 –