2012-09-04 76 views
4

我的模板包含JS,因爲它們被稱爲JS沒有執行,你有一個想法請。AngularJS - 模板:ngInclude指令

例如在我的JS文件script.js中,我有適用於我的templtes中的HTML元素的方法,它不起作用,請一個想法。

例子:

的index.html

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
</head> 
<body ng-app> 
    <ng-include src="'header.html'"></ng-include> 
    <script src="angular.js"></script> 
    <script src="jquery.js"></script> 
    <script src="script.js"></script> 
</body> 
</html> 

了header.html

<div id="header"> 
<div id="logo">AngularJs</div> 
<div id="nav"></div> 
</div> 

的script.js

$(document).ready(function(){ 
    $('#nav').html('<ul><li><a href="">Link<a></li></ul>'); 
}); 

腳本執行很好,我覺得它不找到元素div#n AV。

+0

您能否提供一些細節?例如,您嘗試使用'ngInclude'包含的html文件的核心示例。 – raina77ow

+0

我正在更新該文章的例子,感謝您的幫助 –

回答

2

對不起,我看錯了你的部分問題,我的錯誤。

jQuery的DOM就緒語句可能無法正常工作。你能做的就是在你的ngInclude標籤添加包含你的script.js

欲瞭解更多信息,看看在這裏的文件裏面指定的DOM版A的onload =「FUNCTION_NAME」:http://code.angularjs.org/1.0.1/docs-1.0.1/api/ng.directive:ngInclude

- - 舊帖子---

@YoussefElMontaser,你不必把報價上ngInclude:

<ng-include src="header.html"></ng-include> 

可能是有什麼問題你的腳本不能前進。 讓我知道如果工作。

+0

謝謝你的回答,沒有文件名中的引號不起作用 –

+0

對不起,我的錯誤,我將用可能的解決方案編輯我的文章 – guiligan

+0

好的,謝謝你非常:) –

1

我找到了解決辦法:

http://jsfiddle.net/esjeY/

HTML

<div ng-app=""> 
    <div ng-controller="Ctrl"> 
     <select ng-model="template" ng-options="t.name for t in templates"> 
      <option value="">(blank)</option> 
     </select> 
     url of the template: <tt>{{template.url}}</tt> 
    </div> 
    <div ng-include src="template.url" onload='myFunction()'></div> 
</div> 

JS

function Ctrl($scope) { 

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

    $scope.template = $scope.templates[0]; 

    $scope.myFunction = function() { 

     $('#tpl2').addClass('red');    
    } 
} 

@guiligan:謝謝您幫幫我。

11

由優素福提供的解決方案可以由「多角度」,它不會需要jQuery的:

<!-- template2.html --> 
<script type="text/ng-template" id="template2.html"> 
    <p ng-class="color">Content of template2.html</p> 
</script> 

$scope.myFunction = function() { 
    $scope.color = 'red'; 
} 

http://jsfiddle.net/mrajcok/MfHa6/

在角的世界裏,我們試圖改變模特屬性(例如, $ scope.color)並讓視圖自動更新。我們嘗試不使用ID或jQuery選擇器查找元素,我們嘗試避免在控制器中進行DOM操作 - 例如$('#tpl2')。addClass('red');