Die*_*mio 5 angularjs ng-repeat angularjs-ng-repeat x-editable
我需要向集合添加新项目,使用ngrepeat呈现并使用xeditable使其自动编辑.
顺便说一下,我正在使用"手动触发"方法进行xeditable.
这是HTML
<h4>Angular-xeditable demo</h4>
<div ng-app="app" ng-controller="Ctrl" style="margin: 50px">
<div class="btn btn-default" ng-click="addNew()">+</div>
<ul>
<li ng-repeat="item in array | orderBy:'-value'">
<a href="#" e-form="itemForm" editable-text="item.field">{{ item.field }}</a>
<i ng-show="!itemForm.$visible" ng-click="itemForm.$show()">edit</i>
</li>
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
在这里控制器:
var app = angular.module("app", ["xeditable"]);
app.run(function(editableOptions) {
editableOptions.theme = 'bs3';
});
app.controller('Ctrl', function($scope, $filter) {
$scope.array = [
{value: 1, field: 'status1'},
{value: 2, field: 'status2'},
{value: 3, field: 'status3'},
{value: 4, field: 'status4'}
];
$scope.addNew = function(){
$scope.array.push({value:$scope.array.length+1, field: 'enter text here'});
//MAKE IT EDITABLE????????
}
});
Run Code Online (Sandbox Code Playgroud)
看看这个小提琴中的问题:http://jsfiddle.net/dpamio/hD5Kh/1/
这是一个有效的更新的小提琴。由于该指令的编写方式和ng-repeat工作原理,它需要一个极其hacky的解决方案......
app.controller('Ctrl', function($scope, $filter, $timeout) {
$scope.itemForms = {};
$scope.addNew = function(){
$scope.array.push({value:$scope.array.length+1, field: 'enter text here'});
// Use timeout to force evaluation after the element has rendered
// ensuring that our assignment expression has run
$timeout(function() {
$scope.itemForms[0].$show(); // last index since we sort descending, so the 0 index is always the newest
})
}
Run Code Online (Sandbox Code Playgroud)
ng-repeat 工作原理的背景:ng-repeat 将为每个重复的元素创建一个新的子作用域。e-form该指令使用传入的名称字符串(在本例中为)在该范围内分配一个变量itemForm。如果它更聪明,它会允许对赋值进行表达式求值。(然后我们可以将它分配给父作用域,并在控制器中访问它,但这是另一回事)。
由于我们没有任何方法可以在指令之外访问这个子作用域,所以我们做了一些非常糟糕的事情。我们在 display none 的范围内使用 Mustache 表达式将itemForm变量分配给父范围,以便我们以后可以使用它。然后在我们的控制器中,我们使用查找值来调用itemForm.$show()我们期望的方法。
将这一点讨厌的东西抽象成一个角度指令,我们可以编写以下内容:
.directive('assignFromChild', function($parse) {
return {
restrict: 'A',
link: function(scope, el, attrs) {
scope.$watch(function() { return $parse(attrs.assignFromChild)(scope); }, function(val) {
$parse('$parent.' + attrs.toParent).assign(scope, val);
})
}
};
});
Run Code Online (Sandbox Code Playgroud)
让我们的 HTML 回到:
<ul>
<li ng-repeat="item in array | orderBy:'-value'" assign-from-child="itemForm" to-parent="itemForms[{{$index}}]">
<a href="#" e-form="itemForm" editable-text="item.field">{{ item.field }}</a>
<i ng-show="!itemForm.$visible" ng-click="itemForm.$show()">edit</i>
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)