我对以下情况感到困惑.假设我有一个带行的表.当用户单击表中的按钮时,我希望用户表单向下滑动jQuery并显示包含所选行值的表单.以下是我目前正在做的事情,这没有多大意义:
视图
<tr ng-click="setItemToEdit(item)" slide-down-form>
Run Code Online (Sandbox Code Playgroud)
...
<form>
<input type="test" ng-model={{itemToEdit.Property1}} >
<button ng-click=saveEditedItem(item)" slide-up-form>
<form>
Run Code Online (Sandbox Code Playgroud)
控制
$scope.itemToEdit = {};
$scope.setItemToEdit = function(item) {
$scope.itemToEdit = item;
});
$scope.saveEditedItem = function(item) {
myService.add(item);
$scope.itemToEdit = {};
}
Run Code Online (Sandbox Code Playgroud)
指令 - 上滑/下滑
var linker = function(scope, element, attrs) {
$(form).slideUp(); //or slide down
}
Run Code Online (Sandbox Code Playgroud)
似乎我的指令和我的控制逻辑太过断开了.例如,如果存在保存错误会发生什么?表单已隐藏,因为slideUp事件已完成.在这种情况下,我很可能想要阻止slideUp操作.
我只使用AngularJS大约一个星期,所以我确信有些东西我不见了.
当然,这是一个常见的问题......这是解决这个问题的一种方法:基本上在指令中使用带有$ watch的布尔值来触发表单的切换.除此之外,您只需将表单上的变量设置为要编辑的对象即可.
这是一些伪代码中的一般概念:
//create a directive to toggle an element with a slide effect.
app.directive('showSlide', function() {
return {
//restrict it's use to attribute only.
restrict: 'A',
//set up the directive.
link: function(scope, elem, attr) {
//get the field to watch from the directive attribute.
var watchField = attr.showSlide;
//set up the watch to toggle the element.
scope.$watch(attr.showSlide, function(v) {
if(v && !elem.is(':visible')) {
elem.slideDown();
}else {
elem.slideUp();
}
});
}
}
});
app.controller('MainCtrl', function($scope) {
$scope.showForm = false;
$scope.itemToEdit = null;
$scope.editItem = function(item) {
$scope.itemToEdit = item;
$scope.showForm = true;
};
});
Run Code Online (Sandbox Code Playgroud)
标记
<form show-slide="showForm" name="myForm" ng-submit="saveItem()">
<input type="text" ng-model="itemToEdit.name" />
<input type="submit"/>
</form>
<ul>
<li ng-repeat="item in items">
{{item.name}}
<a ng-click="editItem(item)">edit</a>
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4205 次 |
| 最近记录: |