2015-10-05 19 views
0

我目前有一個服務器使用句柄來創建一個初始的HTML頁面。在這個頁面中,我希望有一個ng-include來更新客戶端上的頁面。ng-include應用程序加載後

但是,每當我的應用程序運行時,它都會加載頁面,所以data-ng-include="template.url"正常情況下會加載template.url。反正有ng-include在加載應用程序後加載這些數據嗎?

這是plunker。查看index.html中的代碼!

+0

你在找什麼可以使用路由器,或更具體地說,一個狀態機。 Angular包含一個路由器軟件包,並且有一個很好的軟件包ui-router,它是一個狀態機https://github.com/angular-ui/ui-router。要麼會工作,但許多人認爲ui-router優於默認的角度路由器。 – Claies

+0

@Claies會看看並回復你! –

+0

我個人不喜歡ng-include,我會做的是構建一個指令並使用ng - 如果提供了類似的回答(因此指令在條件中呈現),或者只是更新指令中的變量,然後在模板上運行$ compile或其他東西來呈現該指令並將其綁定到範圍 –

回答

1

可以使用

ng-if指令

只是檢查它的初始加載,它會使你的生活輕鬆

<ANY ng-if="expression"> 

//your code goes here 

</ANY> 

<ANY ng-if="false"> 

// code will not execute 

</ANY> 

我希望這將幫你

您的代碼

<body> 
<div data-ng-controller="ctrl"> 
    <div data-ng-include="template.url" ng-if="false"> 

    Here is some stuff that I wish to remain until I press the button below. 
    </div> 
    <button type="button" data-ng-click="second()">Press me!</button> 
</div> 

根據您的回答,你應該在你的.js使用條件文件這裏是你修改後的代碼

angular.module('myApp', []) 
    .controller('ctrl', ['$scope', function ($scope) { 

$scope.templates = 
    [ { name: 'first.html', url: 'first.html'}, 
    { name: 'second.html', url: 'second.html'} ]; 

    if (false){ 
     $scope.template = $scope.templates[0]; 
    } 


$scope.second = function() { 
    $scope.template = $scope.templates[1]; 
}; 

$scope.first = function() { 
    $scope.template = $scope.templates[0]; 
}; 

}]); 
+0

有趣的這將工作。不幸的是,它也禁用了其餘的代碼! –

+0

你是否嘗試過這樣?再次檢查答案 –

+0

啊哈哈鬼鬼祟祟的!不幸的是,在'ng-include' div中有邏輯(在我的應用程序中,plunker是一個簡單的例子):( –

0

或者,你可以使用$location您的情況下,但沒有更多的編輯爲您的代碼,我可以爲您提供此解決方案:

  1. index.html文件中刪除你的代碼,所以你的代碼變成了這個樣子:

    <!DOCTYPE html> 
    <html ng-app="myApp"> 
    <head> 
        <script data-require="[email protected]" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script> 
        <script src="script.js"></script> 
    </head> 
    <body> 
        <div data-ng-controller="ctrl"> 
         <div data-ng-include="template.url"></div> 
        </div> 
    </body> 
    </html> 
    

2.Replace您的script.js變成了這個樣子:

angular.module('myApp', []) 
.controller('ctrl', ['$scope', function ($scope) { 

$scope.templates = 
    [ { name: 'init.html', url: 'init.html'}, 
    { name: 'first.html', url: 'first.html'}, 
    { name: 'second.html', url: 'second.html'} ]; 
$scope.template = $scope.templates[0]; 

$scope.second = function() { 
    $scope.template = $scope.templates[2]; 
}; 

$scope.first = function() { 
    $scope.template = $scope.templates[1]; 
}; 
}]); 

3.創建文件init.html與代碼內:

Here is some stuff that I wish to remain until I press the button below. 
<button type="button" data-ng-click="second()">Press me!</button> 
  • ř聯合國。
  • 相關問題