我是AngularJS的新手,我看到其他人提出类似的问题,但答案对我不起作用。而不是劫持这些问题,我想我会为自己打开一个。
我正在创建一个演示应用程序 - 它列出了可以添加或删除的“网站”。我正在使用ng-show属性来显示所需的html div,同时隐藏其他的。
这是后端javascript -
var SiteMaintenanceModule = angular.module("SitesMaintenance", []);
SiteMaintenanceModule.controller("siteCtrl", diveSiteCtrlfn);
function diveSiteCtrlfn($scope) {
// initializing the sites array
$scope.sites = sites;
//initializing the Divs array
$scope.allowedDivs = ["listSiteDiv","addSiteDiv", "editSiteDiv","deleteSiteDiv"];
// setting the first div as selected. This should show the div which lists the sites
$scope.selectedDiv = $scope.allowedDivs[0];
// function to be called with the selected div is to be changed
$scope.setSelectedDiv = function ($divSelectedByUser) {
$scope.selectedDiv = $divSelectedByUser;
}
};
这是html
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="SitesMaintenance">
<head>
<title>List of Dive Sites</title>
<link rel="Stylesheet" href="./../zHelpers/bootstrap/css/bootstrap.css" />
<script src="./../zHelpers/angular.min.js"></script>
<script src="./sites.js"></script>
<script src="./SiteMaintenance.js"></script>
</head>
<body ng-controller="siteCtrl">
<!-- Display the list of sites based on the selectedDiv variable-->
<div id="SiteList" ng-show="{{selectedDiv == 'listSiteDiv'}}">
<h3>List of Sites</h3>
<ul ng-repeat="site in sites" ng-model="sites">
<li>{{site.site}} in {{site.location}}</li>
</ul>
</div>
<!-- Display the add site Div based on the selectedDiv variable-->
<div id="AddSite" ng-show="{{selectedDiv == 'addSiteDiv'}}">
<h3>Add New Site</h3>
<div style="display:block; margin:10px">Site: <input id="inputAddSiteName" /></div>
<div style="display:block; margin:10px">Location: <input id="inputAddSiteLocation" /></div>
</div>
<!-- Display the edit site Div based on the selectedDiv variable -->
<div id="EditSites" ng-show="{{selectedDiv == 'editSiteDiv'}}" style="display:block;margin:20px">
Site Name:<input id="InputEditSiteName" />
Site Location:<input id="InputEditSiteLocation" />
</div>
<div id="controls">
<button id="AddNewSiteButton" ng-click="setSelectedDiv('addSiteDiv')">Add Site</button>
<button id="DeleteSiteButton" ng-click="setSelectedDiv('deleteSiteDiv')">Delete Site</button>
<button id="EditSiteButton" ng-click="setSelectedDiv('editSiteDiv')">Edit Site</button>
</div>
</body>
我可以通过更改语句“$ scope.selectedDiv = $ scope.allowedDivs [0];”中的索引,将可见div设置为我想要的任何内容。在JavaScript中。
单击页面上的任何按钮时,我会更改$ scope.selectedDiv的值,以便更改div的可见性。
但是,无论$ scope.selectedDiv的值是多少,div的可见性都不会改变。事实上,当在chrome中调试时,我看到每个div的ng-show的属性值动态更新为“true”或“false”并且预期,但div仍然显示 - 最初不可见的div似乎有一个class =“ng-hide”属性,它永远不会改变。
我在JavaScript中尝试了$ scope。$ apply(),但这会产生错误。任何帮助将不胜感激。
答案 0 :(得分:4)
您不需要在{{}}
指令指令中使用ng-show
插值,它会直接评估控制器$scope
内的表达式。
ng-show="selectedDiv == 'addSiteDiv'"
ng-show="selectedDiv == 'listSiteDiv'"
ng-show="selectedDiv == 'editSiteDiv'"