AngularJS动态地加载在指令内容

问题描述 投票:1回答:1

我建立一个AngularJS应用程序,我想根据它被称为从动态加载不同的HTML模板。我是新来AngularJS,所以我可能是广泛使用这种方法的印记。

HTML

<div ng-controller="ProjectsCtrl" ng-init="getProjects()">
    <div ng-repeat="project in projects>
        <button ng-click="">Create New Project</button>
        <button ng-click="">Cancel</button>
        <div ng-repeat="task in projects.tasks>
            <button ng-click="">Create New Task</button>
            <button ng-click="">Cancel</button>
        </div>
   </div>
</div>
<focus-pane></focus-pane>

app.js

var projectsApp = angular.module('projectsApp', []);

projectsApp.directive('focusPane', function() {
    return {
        restrict: 'E',
            // this template loading should be dynamic
            templateUrl: '_create_project.html'
    };
});

concernsApp.controller('ProjectsCtrl', function ($scope, $http, ) {
    ...
});

所以,我想要做的是能两件事情在单击“创建新项目”按钮时:

  1. 通过在projecttask对象,并在focusPane指令使用。
  2. 通过在模板的名称在指令动态加载。

我想,在伪代码中,HTML应该是这个样子:

HTML

<div ng-controller="ProjectsCtrl" ng-init="getProjects()">
    <div ng-repeat="project in projects>
        <button ng-click="createProject(project, '_create_project.html')">Create New Project</button>
        <button ng-click="">Cancel</button>
        <div ng-repeat="task in projects.tasks>
            <button ng-click="createProject(task, '_create_task.html')">Create New Task</button>
            <button ng-click="">Cancel</button>
        </div>
   </div>
</div>
<focus-pane></focus-pane>

..和那么我会在ProjectsCtrl声明这些功能。然而,正如我所说,我只是进入AngularJS,我不知道这是正确的道路的。在AngularJS文档我找不到在一个指令动态加载的东西很多信息。

angularjs angularjs-directive
1个回答
0
投票

是较早提出的意见是正确的(这取决于什么情况下你的工作中),但它仍然是可能没有少来创建一个指令,将加载动态模板为您服务。下面是一个例子。 http://jsfiddle.net/joshkurz/T42xQ/5/

.directive('dynamicTemplate', ['$compile', '$templateCache',         function($compile, $templateCache){
return {  
    scope: { templateVar: '@'},
    link: function(scope, element, attrs){

        scope.test = 'Hello World';
        scope.$watch('templateVar', function(newV,oldV){

            if(newV !== undefined){
                var newElement = $compile($templateCache.get(newV).trim())(scope);
                element.html('');
                element.append(newElement[0]);

            }

        });

    }

}

}]);

我发现有时创建指令,他们其实可以有要求来控制哪些数据被请求时。毕竟那是什么呢ngView权?它的一个指令了。你只需要确保您拥有所有数据的任何DOM操作开始之前。

© www.soinside.com 2019 - 2024. All rights reserved.