我在初始化全局变量以在 mycontroller 上的所有函数中使用时遇到一些问题:
这是我到目前为止所做的事情:
JS:
$scope.init = function (table) {
alert("alert 1 : " + table);
$scope.tableName = table;
alert($scope.tableName);
};
tableName = $scope.tableName;
alert("alert 2 : " + tableName);
HTML:
<div ng-init="init('RIGHTTABLE')" ng-controller="DropdownCaptionCtrl">
我的浏览器上有以下顺序的警报:
alert 2 : undefined
alert 1 : RIGHTTABLE
您有解决这个问题的想法吗?
我想要的是按此顺序发出警报:
alert 1 : RIGHTTABLE
alert 2 : RIGHTTABLE
事实上,我希望在所有 Controller 功能中使用一个全局变量 $scope.tableName
,我想在页面启动时初始化它
谢谢
最佳答案
由于 Controller 最初加载,您的 init 函数在变量未定义后被调用,您可以做的是
$scope.init = function (table) {
alert("alert 1 : " + table);
$scope.tableName = table;
alert($scope.tableName);
alert("alert 2 : " + $scope.tableName);
};
更新:
如果您想在所有 Controller 中使用该变量,请选择 Service
其他选项是使用 $rootScope,
$scope.init = function (table) {
alert("alert 1 : " + table);
$rootScope.tableName = table;
alert($rootScope.tableName);
alert("alert 2 : " + $rootScope.tableName);
};
然后您将能够使用$rootScope.tableName
在任何 Controller 中访问
关于javascript - ng-init 和 ng-controller 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33519461/