简体   繁体   English

指令中templateUrl的角路由

[英]Angular routing for templateUrl in directives

I'm building an angular application in MVC. 我正在MVC中构建一个角度应用程序。 I have created a angular directive in my application as given below. 我在应用程序中创建了一个角度指令,如下所示。

app.directive('clusterButton', function () {
return {
    restrict: 'E',
    scope: {
        clusterInfo: '=info'
    },
    templateUrl: function(elem, attr){
        return 'Views/NgTemplates/ClusterButton.html';
    }
};
});

I have created the ClusterButton.html in Views/NgTemplates folder. 我已经在Views / NgTemplates文件夹中创建了ClusterButton.html。 I used this directive in index.cshtml file as given below. 我在index.cshtml文件中使用了此指令,如下所示。

<div ng-controller="homeController" class="row clusters_main">
        <div ng-repeat="cluster in Clusters" ng-init="selectedClusterId = '#'">
            <cluster-button info="cluster"></cluster-button>
        </div>
    </div>

Now the angular directive is rendering properly in my view. 现在,角度指令在我的视图中可以正确渲染。 But I don't like to specify the full template url ['Views/NgTemplates/ClusterButton.html'] in the directive. 但我不想在指令中指定完整的模板网址['Views / NgTemplates / ClusterButton.html']。 I need to shorten it like template/ClusterButton. 我需要像template / ClusterButton一样缩短它。 It need to track in the angular js routing and need to redirect to 'Views/NgTemplates/ClusterButton.html'. 它需要跟踪有角度的js路由,并需要重定向到“ Views / NgTemplates / ClusterButton.html”。 I don't want to make the mvc routing involvement in this process. 我不想让MVC路由参与此过程。 Is anybody know a proper way to implement this? 有人知道实现此目标的正确方法吗? I browsed a lot of sites. 我浏览了很多网站。 But most of it says about view rendering using ng-view. 但是大多数内容都涉及使用ng-view进行视图渲染。 I want to specify the template url of directive in angular routing. 我想在角度路由中指定指令的模板网址。

As far as my knowledge goes Angular doesn't have anything built in to address this, however there are a few strategies to handle your case: 据我所知,Angular并没有内置任何解决方案,但是有一些策略可以处理您的情况:

  1. You can use something like "grunt-angular-templates" which takes your template files and drops it in a javascript file to have them "cached". 您可以使用“ grunt-angular-templates”之类的东西,将模板文件拖放到javascript文件中以使其“缓存”。 It uses the path to the template as the cache key, so you could just change your path to "ClusterButton.html" and make sure you handle the "angular-template' to generate the same key. 它使用模板的路径作为缓存键,因此您只需将路径更改为“ ClusterButton.html”,并确保处理“ angular-template”以生成相同的键。

  2. Use the <base /> tag. 使用<base />标记。 The problem is that all your static resources will be relative to that. 问题在于您所有的静态资源都将与此相对。

  3. Just create a constant that holds the part of the path that repeats every time and build the path with that like: templateUrl: myConstats.directivesPath + '/ClusterButton.html' 只需创建一个常量,该常量将保留每次重复的路径部分,并使用以下方式构建路径: templateUrl: myConstats.directivesPath + '/ClusterButton.html'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM