我正在学习第一个Angular项目,并遇到了一个问题。
目标:在使用ng-include放置的给定.html模板中点击链接时,我希望它更改$ scope.selectedLocation的值
问题: $ scope.selectedLocation的值不会更改。
我读到ng-include创建了一个子范围,因此为了更改父范围变量,可以将$ parent放在值的前面。我试过这个并没有用。
主要索引页面:
<body ng-app="photoApp" id="bodyDiv" >
<div ng-controller="PhotoGallery">
<div>
<ng-switch on="selectedLocation" >
<div ng-switch-when="home" >
<div ng-include="'home.html'"></div>
</div>
<div ng-switch-when="loc1">
<div ng-include="'file1.html'"></div>
</div>
<div ng-switch-when="loc2">
<div ng-include="'file2.html'"></div>
</div>
</ng-switch>
</div>
</div>
</body>
home.html代码:
<div class="container-fluid">
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6">
<a href="#" ng-click="selectedLocation='loc1'">
Location 1
</a>
</div>
<div class="col-lg-6 col-md-6 col-sm-6">
<a href="#" ng-click="selectedLocation='loc2'">
Location 2
</a>
</div>
</div>
</div>
photoApp.js代码:
var photoApp= angular.module('photoApp', []);
westonPhotographyApp.controller('PhotoGallery', function($scope)
{
$scope.selectedLocation ="home";
}
答案 0 :(得分:1)
问题是您要绑定到继承范围中的原语。要修复它,你应该传递一个对象:
westonPhotographyApp.controller('PhotoGallery', function($scope)
{
$scope.vm = {
selectedLocation: "home"
}
}
HTML
<div class="container-fluid">
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6">
<a href="#" ng-click="vm.selectedLocation='loc1'">
Location 1
</a>
</div>
<div class="col-lg-6 col-md-6 col-sm-6">
<a href="#" ng-click="vm.selectedLocation='loc2'">
Location 2
</a>
</div>
</div>
ng-include
创建一个新范围,通过原型链继承父(控制器)范围。在javascript中,您无法替换阴影继承属性的值。传递对象时,您可以在指向对象的指针上更改属性。
https://github.com/angular/angular.js/wiki/Understanding-Scopes
答案 1 :(得分:0)
您似乎错误地命名了您的app变量。名称westonPhotographyApp
photoApp
或反之亦然:
var photoApp = angular.module('photoApp', []);
photoApp.controller('PhotoGallery', function($scope) {
$scope.selectedLocation ="home";
}
无论如何,你可以改进你的设计: 您可以使用controllerAs语法。它命名您的控制器并使其在后代范围内可访问:
指数:
<div ng-controller="PhotoGallery as pgCtrl">
<div>
<ng-switch on="selectedLocation" >
<div ng-switch-when="home" >
<div ng-include="'home.html'"></div>
...
主页:
<div class="container-fluid">
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6">
<a href="#" ng-click="pgCtrl.selectedLocation='loc1'">
Location 1
</a>
</div>
<div class="col-lg-6 col-md-6 col-sm-6">
<a href="#" ng-click="pgCtrl.selectedLocation='loc2'">
Location 2
</a>
</div>
</div>
</div>
使用您的控制器:
photoApp.controller('PhotoGallery', function() {
var vm = this;
vm.selectedLocation ="home";
}