我尝试在指令中使用 templateUrl 来加载部分内容,但是当访问模板的 URL 时,我被重定向回/。因此,部分加载整个页面而不是请求部分。
添加到购物车.js
.directive('addToCart', function() {
return {
restrict: 'E',
scope: {
},
replace: false,
templateUrl: 'src/common/add-to-cart/add-to-cart.tpl.html',
link: function(scope, element, attrs) {
}
};
});
app.js
$urlRouterProvider.otherwise( '/' );
为什么会发生这种情况以及如何解决?
最佳答案
为了解决这个问题,我必须使用 id 作为 templateUrl 而不是正确的路径。我不完全确定它是否总是这样,或者是否是因为我使用的是 grunt Angular 模板引擎,但此更改解决了问题:
templateUrl: 'add-to-cart/add-to-cart.tpl.html',
另一个解决方案是注入(inject) templateCache 并通过它加载模板,使用完全相同的 id 和完全相同的结果。所以总而言之,我认为它做了完全相同的事情。
.directive('addToCart', ['$templateCache', function($templateCache) {
...
templateUrl: $templateCache.get('add-to-cart/add-to-cart.tpl.html'),
...
}]);
关于javascript - 指令 templateUrl 重定向到/,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26841136/