[angular]指令之4templateUrl

<!DOCTYPE html>
<html lang="en" ng-app="testDirectiveTemplateUrl">
<head>
    <meta charset="UTF-8">
    <title>测试DirectiveTemplateUrl</title>
    <script src="../frameWork/angular.js"></script>
    <script src="../testDirective/testDirectiveTemplateUrl.js"></script>
    <script type="text/ng-template" id="templateUrlTwo">
        <div>
            <span>我是来自templateUrlTwo的内容</span>
        </div>
    </script>
    <script type="text/ng-template" id="templateUrlDynamic1">
        <div>
            <span>我是来自动态templateUrlDynamic1的内容</span>
        </div>
    </script>
    <script type="text/ng-template" id="templateUrlDynamic2">
        <div>
            <span>我是来自动态templateUrlDynamic2的内容</span>
        </div>
    </script>
</head>
<body>

<h3>内容1:正常的模版来源</h3>
<template-url-normal></template-url-normal>

<h3>内容2:模版来自script标签</h3>
<template-url-from-script></template-url-from-script>

<h3>内容3:模版来自script标签,并且动态的模版</h3>
<template-url-dynamic></template-url-dynamic>
<template-url-dynamic template-index="1"></template-url-dynamic>
<template-url-dynamic template-index="2"></template-url-dynamic>
</body>
</html>
/**
 * 由于directive在angular中的地位之重,所以得认真对待。但理解难啊,所以决定逐个属性进行实例分析
 * directive实例分析第四篇:templateUrl
 * Created by liyanq on 16/12/21.
 */

/**templateUrl很重要的属性,正常情况下,应该都会用到吧。
 * 1,templateUrl的值'directive.html', // or // function(tElement, tAttrs) { ... }。
 * 2,templateUrl函数执行的时机要早于link,并且如果找不到url的话,link就不执行了(很危险啊。。。)
 * 3,templateUrl的大小写得注意。
 * */
var app = angular.module("testDirectiveTemplateUrl",[]);
app.directive("templateUrlNormal",function($templateCache){
    var dir = {};
    dir.restrict = "E";
    dir.replace = true;
    dir.templateUrl = $templateCache.get("templateUrlOne");
    return dir;
}).directive("templateUrlFromScript",function(){
    var dir = {};
    dir.restrict = "E";
    dir.replace = true;
    dir.templateUrl = "templateUrlTwo";
    return dir;
}).directive("templateUrlDynamic",function(){
    var dir = {};
    dir.restrict = "EA";
    dir.replace = true;
    dir.scope=true;
    dir.templateUrl = function(scope,attr){
        if (attr["templateIndex"]){//如果解析不了,得给个默认的
            return "templateUrlDynamic"+attr["templateIndex"];
        }
        return "templateUrlDynamic1";
    };
    return dir;
}).run(function($templateCache){
    $templateCache.put("templateUrlOne","../templates/testTemplateUrlOne.html");
});


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值