Ng-show似乎不能使用全局变量
ng-show does not appear to work with global variables
我试图根据$http服务的响应显示div的内容。AJAX调用工作得很好,不是这里的问题。但是,我无法更新我想要的控制器变量(intFlag)以获得所需的行为。我认为创建一个全局变量可以解决这个问题,尽管我不想这样做。
这里有一个类似的问题:(AngularJS: ng-show usage),但是解决方案,我在很多其他地方看到过,似乎不适合我。这似乎是一个相当标准的程序。最初,我认为这只是一个作用域问题,但即使是全局变量尝试也不起作用。这可能是因为视图没有根据全局变量的变化进行更新。我还在学习Angular。
<html ng-app="myapp">
<head>
<script type="text/javascript">
var intFlag = 0;
var app = angular.module('myapp', []);
app.controller('AController', function ($scope, $http)
{ //I've tried: var this.intFlag = 0; here already
this.CreateUser=function()
{ //scope changes here, right?
$http({
method: 'POST',
url: 'some url', //pseudocode
data: someData, //pseudocode
headers: { 'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response)
{ intFlag = 1; //global variable
//Ideally I want to update a variable that is in the scope for the controller
}, function errorCallback(response) {
});
};
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5 /angular.min.js"></script>
</head>
<body ng-controller="AController as Ctrl">
<div>
<button type="button" ng-click="Ctrl.CreateUser()" >Create User</button>
<div ng-show="intFlag === 1">
<p>Congratulations!</p>
</div>
</div>
</body>
</html>
您需要将该变量添加到控制器上下文(this
),因为您正在使用controllerAs
,然后将其与控制器别名(如Ctrl.intFlag
)一起使用。此外,我想说,从控制器中删除$scope依赖关系,这对混合$scope
&this
一起。
标记
ng-show="Ctrl.intFlag"
var app = angular.module('myapp', []);
app.controller('AController', function ($http)
{
var self = this;
self.intFlag = intFlag;
self.CreateUser=function()
{ //scope changes here, right?
$http({
method: 'POST',
url: 'some url', //pseudocode
data: someData, //pseudocode
headers: { 'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response)
{ self.intFlag = 1;//global variable
//Ideally I want to update a variable that is in the scope for the controller
}, function errorCallback(response) {
});
};
});
您需要有一个控制器上下文变量,如'self':
控制器
app.controller('AController', function($scope, $http) { //I've tried: var this.intFlag = 0; here already
var self = this;
self.intFlag = 0;
this.CreateUser = function() { //scope changes here, right?
$http({
method: 'POST',
url: 'some url', //pseudocode
data: someData, //pseudocode
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function successCallback(response) {
self.intFlag = 1; //global variable
//Ideally I want to update a variable that is in the scope for the controller
}, function errorCallback(response) {});
};
});
然后像这样在上下文中引用变量: