2013-05-06 45 views
16

在我的Angular应用程序中,我试图理解将我的页面拆分为组件的正确方法。将角模板拆分为多个小模板

进行更改之前的页面类似于:

<div id='settings'> 

    <p class='controlGroup' ng-controller="FirstCtrl"> 
    <label class='control-label'>First Control</label> 

    <div class="control"> 
     <!-- some inputs --> 
    </div> 
    </p> 

    <p class='controlGroup' ng-controller="SecondCtrl"> 
    <label class='control-label'>Second Control</label> 

    <div class="control"> 
     <!-- some inputs --> 
    </div> 
    </p> 

    </p> 


    <button id='saveBtn' class='saveButton' ng-click='saveSettings()'>Save Changes</button> 

</div> 

虽然控制逻辑分离到两个不同的控制器,我想他们的模板分开为好,所以这将是易于重用他们或将它们移动到不同的位置。

我看到很多选项:ng-includescript标签等

什么是这样做的正确方法?

+2

不想要勾选正确的答案? – Amir 2014-10-14 12:14:44

回答

0

指令是对角创建可重用组件的自然选择:http://docs.angularjs.org/guide/directive

+9

是的,但是对于这个简单的问题,指令非常复杂。他们应该与你所说的“可重用”的东西不能分离视图一起使用。 – Amir 2013-05-06 12:07:01

13

采用NG-包括你可以有不同的模板,只需将它们注入用它你的DOM的部分进入,当你想是很好的时间根据点击导航按钮或变量等不同情况加载不同的视图,请注意,ng-include也编译模板,以便您可以在模板中使用控制器和其他角度特征和指令,以下是来自angularjs文档的示例:

这里是你的主要html:

<!doctype html> 
<html ng-app> 
    <head> 
    <script src="http://code.angularjs.org/1.0.6/angular.min.js"></script> 
    <script src="script.js"></script> 
    </head> 
    <body> 
    <div ng-controller="Ctrl"> 
     <select ng-model="template" ng-options="t.name for t in templates"> 
     <option value="">(blank)</option> 
     </select> 
     url of the template: <tt>{{template.url}}</tt> 
     <hr/> 
     <div ng-include src="template.url"></div> 
    </div> 
    </body> 
</html> 

这里是JS:

function Ctrl($scope) { 
    $scope.templates = 
    [ { name: 'template1.html', url: 'template1.html'} 
    , { name: 'template2.html', url: 'template2.html'} ]; 
    $scope.template = $scope.templates[0]; 
}