Javascript 在这三种方法中,哪一种是有效的?为什么有三种不同的方法来做同样的事情?在哪里使用哪一种?
通过调查,我发现有3种方法可以在angular中获得自定义标记或指令 1) 在templateUrl中将文件直接指定为文件的位置Javascript 在这三种方法中,哪一种是有效的?为什么有三种不同的方法来做同样的事情?在哪里使用哪一种?,javascript,angularjs,Javascript,Angularjs,通过调查,我发现有3种方法可以在angular中获得自定义标记或指令 1) 在templateUrl中将文件直接指定为文件的位置 /* controller */ var foundation = angular.module('foundation', []); foundation.directive('viewdesign', function() { return { restrict : 'EA', templateUrl: "templates/viewdesign.h
/* controller */
var foundation = angular.module('foundation', []);
foundation.directive('viewdesign', function() {
return {
restrict : 'EA',
templateUrl: "templates/viewdesign.html"
};
});
2) 在模板中给出字符串化的表单
/* controller*/
var foundation = angular.module('foundation', []);
foundation.directive('viewdesign', function() {
return {
restrict : 'EA',
template: <stringified template file contents>
};
});
/*控制器*/
VaR基金会=角度。模块(基金会),[];
基础:指令(视图设计),函数()
返回{
限制:“EA”,
模板:
};
});
3) 将字符串化表单存储在templatecache中并将其馈送
/* controller */
var foundation = angular.module('foundation', ["templates/viewdesign.html"]);
angular.module("templates/viewdesign.html", []).run(["$templateCache" ,
function( $templateCache)
{ $templateCache.put("templates/viewdesign.html",
<stringified template file contents>
);
}]);
foundation.directive('viewdesign', function() {
return {
restrict : 'EA',
templateUrl: "templates/viewdesign.html"
};
});
/*控制器*/
VaR基金会=角度。模块(基金会),[ [模板/ VIEW Dealth.html ] ];
angular.module(“templates/viewdesign.html”,[])。运行([“$templateCache”,
函数($templateCache)
{$templateCache.put(“templates/viewdesign.html”,
);
}]);
基础:指令(视图设计),函数()
返回{
限制:“EA”,
templateUrl:“templates/viewdesign.html”
};
});
因此,我们可以访问html中的模板,如下所示
<div ng-app="foundation">
<viewdesign></viewdesign>
</div>
我的怀疑是
第一个将在第一次使用指令时使用AJAX请求下载模板。它允许通过编辑HTML文件轻松定制模板 第二种方法通过将模板直接存储在指令中来避免额外的AJAX请求。这将迫使您修改指令本身以自定义模板
第三种方法结合了上述两种技术:它从URL获取模板,但会立即填充缓存,因此AJAX请求是不必要的。这很有用,因为您可以轻松提供两个版本的JS文件:一个包含指令而不包含模板(允许用户根据需要自定义模板),另一个包含指令和包含其模板的预填充缓存(如果用户对标准模板满意).第一种和第二种方法是相同的。唯一的区别是第一种方法使用外部模板,第二种方法使用内联模板。为了更好地组织代码,最好使用外部模板,但这是对服务器进行额外的ajax调用 外部模板
var foundation = angular.module('foundation', []);
foundation.directive('viewdesign', function() {
return {
restrict : 'EA',
templateUrl: "templates/viewdesign.html"
};
});
viewdesign.html
<h1>Hi to you</h1>
你好
内联模板
var foundation = angular.module('foundation', []);
foundation.directive('viewdesign', function() {
return {
restrict : 'EA',
template: '<h1>Hi to you</h1>'
};
});
<代码> var基础=角。模块(‘基金会’,[]);
基础:指令(视图设计),函数()
返回{
限制:“EA”,
模板:“你好”
};
});
第三种技术是在第一次使用模板之前将其预加载到缓存中
$templateCache.put("templates/viewdesign.html",'<h1>Hi to you</h1>');
$templateCache.put(“templates/viewdesign.html”,“您好”);
编写一些测试并亲自查看: