我正在尝试根据 $http 服务的响应显示 div 的内容。 AJAX 调用工作正常,不是这里的问题。但是,我无法更新我想要的 Controller 变量(intFlag)以获得所需的行为。 我认为创建一个全局变量可以解决问题,尽管我不想这样做。
这里有一个类似的问题:( AngularJS : ng-show usage ),但是我在许多其他地方看到的解决方案似乎对我不起作用。这似乎是一个相当标准的程序。最初,我认为这只是一个范围问题,但即使是全局变量尝试也不起作用。这可能是因为 View 不会响应全局变量的更改而更新。我仍在学习 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>
最佳答案
您需要在使用 controllerAs
时将该变量添加到 Controller 上下文 (this
),然后将其与 Controller 别名(例如 Ctrl.intFlag
)一起使用>。另外,我想说的是,从 Controller 中删除 $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) {
});
};
});
关于javascript - ng-show 似乎不适用于全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38131929/