简体   繁体   中英

Angular routing for templateUrl in directives

I'm building an angular application in 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. I used this directive in index.cshtml file as given below.

<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. I need to shorten it like template/ClusterButton. It need to track in the angular js routing and need to redirect to 'Views/NgTemplates/ClusterButton.html'. I don't want to make the mvc routing involvement in this process. 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. 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:

  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". 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.

  2. Use the <base /> tag. 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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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