AngularJS - 模板: ngInclude指令

4

我的模板包含JS,但是当它们被调用时JS并没有执行,请问您有什么想法吗?

例如,在我的JS文件script.js中,我有一些方法应用于我的模板中的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#nav。

请问您能提供一些细节吗?例如,您尝试使用ngInclude包含的HTML文件的核心示例。 - raina77ow
我正在更新帖子并附上一个例子,感谢你的帮助。 - Youssef El Montaser
3个回答

11

Youssef提供的解决方案可以“更加Angular化”,而且不需要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';
}

在Angular世界里,我们尝试改变模型属性(例如$scope.color),并让视图自动更新。我们尝试不通过ID或jQuery选择器查找元素,并且避免在控制器中进行DOM操作——例如$('#tpl2').addClass('red');

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


2
抱歉,我误读了您问题的一部分,是我的错误。
jQuery的DOM准备语句可能不会正常工作。您可以在ngInclude标签上添加一个onload ="FUNCTION_NAME",其中包含您在script.js中指定的DOM修改内容。
有关更多信息,请查看此处的文档:http://code.angularjs.org/1.0.1/docs-1.0.1/api/ng.directive:ngInclude ---旧帖子---
@YoussefElMontaser,您不必在ngInclude上加引号:
<ng-include src="header.html"></ng-include>

可能这就是你的脚本无法继续执行的原因。 如果可以的话,请告诉我是否有效。


谢谢您的回答,没有文件名中的引号是不起作用的。 - Youssef El Montaser
抱歉,我的错误,我将编辑我的帖子并提供可能的解决方案。 - guiligan
我添加了一个名为myFunction的函数,但它不起作用。函数如下:myFunction(){ $('#nav').html('<ul><li><a href="">Link<a></li></ul>'); } <ng-include src="'header.html'" onload='myFunction'></ng-include>谢谢。 - Youssef El Montaser
这是一个基于官方angularjs示例的示例: http://jsfiddle.net/HVzgX/。谢谢 - Youssef El Montaser
太好了,我找到了解决方案,http://jsfiddle.net/esjeY/@guiligan,谢谢你的帮助。 - Youssef El Montaser

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:感谢你的帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接