gpt4 book ai didi

javascript - 我的 Controller 变量的奇怪行为

转载 作者:行者123 更新时间:2023-12-03 05:44:20 25 4
gpt4 key购买 nike

我是这个领域的新手,正在尝试编写一些代码。以下是我的测试:

js:

(function() {
angular.module('dashboard', []);
})();

(function() {
'use strict';
angular.module('dashboard').controller('mainControl', function() {
var self=this;
self.logged = true;
alert("hello");
});
})();

html:

<!DOCTYPE html>
<html lang="en" ng-app='dashboard'>
<head>
<meta charset="utf-8">
<title>Shen's Event Planner</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="all.js"></script>
<!--link rel="stylesheet" href="main.css"-->
</head>
<body ng-controller="mainControl">
<div>
<div ng-show="mainControl.logged">

<button type="button" class="btn" data-toggle="modal" data-target=".signUp">Sign Up</button>
<button type="button" class="btn" data-toggle="modal" data-target=".logIn">Log In</button>
</div>
<div ng-hide="mainControl.logged">
<button type="button" class="btn" data-toggle="modal" data-target=".createEvent">Create Event</button>
<button>Sign Out</button>
</div>
</div>
</body>
</html>

可运行的代码在这里 https://plnkr.co/edit/ci5FCx4sASTzikgpn0gb?p=preview我运行它并发出警报,这意味着变量已设置。但无论我在 js 文件中将 this.logged 设置为 true 或 false 。输出都是一样的。你能告诉我原因吗?谢谢!

我知道 $scope 是个好主意,但我在这里测试其他方法。

最佳答案

你应该使用$scope,

(function() {
'use strict';
angular.module('dashboard').controller('mainControl', function($scope) {
$scope.logged = true;
alert("hello");
});
})();

<强> DEMO

如果您使用的是 Controller As 语法,请按如下方式更改代码,

 <body ng-controller="mainControl as mc">
<div>
<div ng-show="mc.logged">
<button type="button" class="btn" data-toggle="modal" data-target=".signUp">Sign Up</button>
<button type="button" class="btn" data-toggle="modal" data-target=".logIn">Log In</button>
</div>
<div ng-hide="mc.logged">
<button type="button" class="btn" data-toggle="modal" data-target=".createEvent">Create Event</button>
<button>Sign Out</button>
</div>
</div>
</body>

关于javascript - 我的 Controller 变量的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40392565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com