2015-10-17 44 views
0

我有一個index.html頁用下面的代碼AngularJS改變從視圖

<html> 
<head> 
<title>{{title}}</title> 
</head> 
</html> 

頁面標題和我有一個view.html

<div ng-controller="changeCtrl"> 
<input type="text" ng-model="page-title"> 
</div> 

路由完美的作品,

現在,我怎樣才能將page-title模型綁定到{{title}}而我鍵入?

由於

+0

你有沒有嘗試: http://stackoverflow.com/questions/12506329/how-to-dynamically-change-header-based-on-angularjs-partial-view/ 12506795#12506795 ? –

+0

ng-model =「$ root.title」'和ng-app html標籤 – YOU

+0

@YOU我將如何在ng模型上添加myForm.FirstName呢? – user3052526

回答

1

爲避免使用$ rootScope或移動ng-app,請使用服務來處理設置頁面標題。在下面的片段中,我給出了一個使用服務的例子。

angular.module('app', []) 
 

 
.service('PageService', function($window) { 
 
    return { 
 
     setTitle: function (newTitle) { $window.document.title = newTitle; } 
 
    }; 
 
}) 
 

 
.controller('ChangeCtrl', function(PageService) { 
 
    this.setPageTitle = PageService.setTitle; 
 
});
<html> 
 
    <head> 
 
     <title>My Awesome App</title> 
 
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
    </head> 
 
    <body ng-app="app"> 
 
     <div ng-controller="ChangeCtrl as ctrl"> 
 
      <label>{{ctrl.title}}</label> 
 
      <input type="text" ng-model="ctrl.title" ng-change="ctrl.setPageTitle(ctrl.title)"> 
 
     </div> 
 
    </body> 
 
</html>

1

首先,因爲表達式是正確的HTML根元素下,角度的應用程序必須「覆蓋」這個元素。所以NG-應用應該是在html元素:

<html ng-app="app"> 

其次,由於表達式是任何控制器範圍之外,角長相對於在$ rootScope的title字段。因此,您需要在由控制器處理的視圖內部輸入字段來修改$ rootScope屬性的值。

不能做到:

<input ng-model="title" /> 

將設置字段title控制器上的範圍。然而,可以做的是通過在根作用域中定義的作用域繼承來訪問一個對象,並修改它的一個屬性。

angular.module('app').run(function($rootScope) { 
    $rootScope.page = { 
     title: 'default title' 
    }; 
}); 

然後改變表達式來訪問該對象的標題屬性:

<title>{{ page.title }}</title> 

和在控制器視圖:

<input ng-model="page.title" /> 
所以,firstmake確保這樣的對象在根範圍存在
+0

這是我原來的解決方案,直到我讀到使用$ rootScope皺起了眉頭。但解決方案完美地工作。 – user3052526

0

使您在ng控制器範圍內的所有數據綁定,即{{title}}應該位於內部,否則您將移動到您的ng控制器以html標記,:)