首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AngularJS - Templates : ngInclude指令

AngularJS - Templates : ngInclude指令
EN

Stack Overflow用户
提问于 2012-09-04 18:57:47
回答 3查看 26.5K关注 0票数 4

我的模板包含JS,因为它们被称为JS不执行,请您有一个想法。

例如,在我的JS文件script.js中,我有一些方法应用于我的模板中的HTML元素,但它不起作用,请注意。

示例:

index.html

代码语言:javascript
复制
<!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

代码语言:javascript
复制
<div id="header">
<div id="logo">AngularJs</div>
<div id="nav"></div>
</div>

script.js

代码语言:javascript
复制
$(document).ready(function(){
    $('#nav').html('<ul><li><a href="">Link<a></li></ul>');
});

脚本执行得很好,我觉得它找不到元素div#nav。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-09-04 20:58:27

对不起,我看错了你的问题的一部分,是我的错。

jQuery的DOM ready语句可能无法正常工作。您可以做的就是在ngInclude标记上添加一个onload="FUNCTION_NAME“,其中包含您在script.js中指定的DOM版本

有关更多信息,请查看此处的文档:http://code.angularjs.org/1.0.1/docs-1.0.1/api/ng.directive:ngInclude

-旧帖子

@YoussefElMontaser,你不需要在ngInclude上加引号:

代码语言:javascript
复制
<ng-include src="header.html"></ng-include>

也许这就是你的脚本不能前进的问题所在。如果成功了,请告诉我。

票数 2
EN

Stack Overflow用户

发布于 2012-10-09 23:06:59

Youssef提供的解决方案可以变得“更有角度”,并且不需要jQuery:

代码语言:javascript
复制
<!-- 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或红色选择器来查找元素,并且尽量避免在控制器中进行DOM操作--例如,$(‘#tpl2’).addClass(‘jQuery’);

票数 11
EN

Stack Overflow用户

发布于 2012-09-05 17:53:31

我找到了解决方案:

http://jsfiddle.net/esjeY/

HTML

代码语言:javascript
复制
<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

代码语言:javascript
复制
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 :感谢您的帮助。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12262067

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档