我一直试图通过Angular方式做事,而我目前正试图弄清楚指令的正确使用以及它们与应用程序整体生态系统的关系。目前,我试图处理具有不同的可编辑元素的表单的基本逻辑,以及提交或恢复表单状态的取消/保存按钮。
这是我拥有的,有效的。我正在使用Slim模板和CoffeeScript,所以我会尝试将其清理成简单的HTML和JS,所以请假设任何破解应用程序的语法错误都是此帖子的错误输入的结果
# excerpt of the template
<div my-form ng-repeat="band in bands">
<div class="band-name">
{{band.name}}
</div>
<div class="edit-band" ng-click="editBand(band)">
Click to edit
</div>
<div ng-if="editingBand != band">
{{band.tagline}}
</div>
<div ng-if="editingBand == band">
<form class="form-horizontal" ng-submit="updateBand(band)">
<input type="text" ng-model="band.tagline" />
<input class="btn btn-default" type="submit" />
</form>
</div>
<div ng-if="uncommitedChanges">
<button ng-click="saveChanges()">Save</button>
<button ng-click="cancelChanges()">Cancel</button
</div>
</div>
---------------excerpt of controller
# during init
$scope.bands = bands;
$scope.originalBands = angular.copy(bands);
$scope.uncommittedChanges = false
$scope.editBand = function(band) {
$scope.editingBand = band;
}
$scope.updateBand = function(band) {
$scope.editingBand = null;
$scope.uncommittedChanges = true;
}
$scope.cancelChanges = function(){
$scope.bands = angular.copy($scope.originalBands);
$scope.uncommittedChanges = false
}
$scope.saveChanges = function(){
$scope.uncommittedChanges = true;
// bands are sent to the service that performs the update against the API
}
所以,这一切都有效,但这是一种适当的AngularJS做事方式吗?我觉得很多逻辑应该被分成一个指令,因为它会更加可重用,但我对如何启动它有点不清楚。就此而言,我的预感是正确的,我甚至都不肯定。指导真的很感激。
答案 0 :(得分:0)
这正是AngularJS中的工作方式:) 如果你看到你可以将一些代码封装到指令中以重用它 - 那就去做吧。但我不认为除了你之外,任何人都可以说出你可以在该例子的代码中重用的内容:)也许你想把ng-repeat里面的代码放到指令中。
P.S。:ng-if
是强有力的指令,与ng-show
的工作有所不同,我建议你阅读它。
答案 1 :(得分:0)
所以这最终既不是超级复杂也不是太宽而无法简单回答。它可能不是最好的方法,但它是一个开始。欢迎提出建议!
我在阅读几篇博客时注意到,您可以定义一个负责指令的控制器。知道了这个问题的解决方案,&#34;如何将我的功能移出控制器并进入指令?&#34;可以回答,&#34;你不能将它们移动到专用于你指令的控制器中。&#34;
在模板中,我称之为:
<div id="show-bands" class="col-md-8" bands-form bands="bands"></div>
我的指示仍然非常简单。
myApp.directive 'bandsForm', () ->
return {
scope: {
bands: '=bands'
}
templateUrl: 'directives/bands/band_form.html'
controller: 'BandFormCtrl'
}
我使用scope: { bands: '=bands' }
创建隔离范围,这意味着我将bands
属性设置为等于调用指令时的任何模型都将传递给指令。这相当于Rails ERB模板中的<%= render 'templates/my_template', bands: @bands %>
。
最后,BandFormCtrl
是一个专门用于该指令的新控制器。它包含此重构之前共享控制器中的所有内容。只要bands
被定义并且能够传递下去,一切都会有效。