2016-03-14 52 views
1

我在學習第一個Angular項目時遇到了問題。Angular.js在ng-include html模板中沒有作用域

目標:當單擊放置在一個給定的.html模板的鏈接NG-包括,我希望它改變$ 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

你似乎已經名不副實您的應用程序變量。無論名稱westonPhotographyAppphotoApp反之亦然:

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"; 
} 
+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