我想在 angularjs 中编写“就地编辑”指令。我希望该指令是可重用的,因此我对该指令有以下要求:
- 它必须是可以装饰任何元素的属性,这是有意义的(div,span,li)
- 它必须支持编辑按钮,单击该按钮会将设置的显示元素更改为输入文件。一个对象的典型属性,例如联系人(号码、姓名)
我发现指令中范围可见性的欺骗行为可以在这个小提琴http://jsfiddle.net/honzajde/ZgNbU/1/中看到。
- 在指令中注释掉:显示模板和范围 -> 联系人号码和联系人姓名
- 在指令中注释掉:scope -> contact.number only 被显示
- 不注释掉任何东西->什么都不显示
=> 当两者都被注释掉时,只需将模板添加到指令中,即使未使用模板,它也会呈现contact.number。
我想问游戏规则是什么?
<div>
<div ng-controller="ContactsCtrl">
<h2>Contacts</h2>
<br />
<ul>
<li ng-repeat="contact in contacts">
<span edit-in-place="" ng-bind="contact.number"></span> |
<span edit-in-place="" >{{contact.name}}</span>
</li>
</ul>
<br />
<p>Here we repeat the contacts to ensure bindings work:</p>
<br />
<ul>
<li ng-repeat="contact in contacts">
{{contact.number}} | {{contact.name}}
</li>
</ul>
</div>
</div>
var app = angular.module( 'myApp', [] );
app.directive( 'editInPlace', function() {
return {
restrict: 'A',
//scope: { contact:"=" },
template: '<span ng-click="edit()" ng-bind="value"></span><input ng-model="value"></input>',
link: function ( $scope, element, attrs ) {
// Let's get a reference to the input element, as we'll want to reference it.
var inputElement = angular.element( element.children()[1] );
// This directive should have a set class so we can style it.
element.addClass( 'edit-in-place' );
// Initially, we're not editing.
$scope.editing = false;
// ng-click handler to activate edit-in-place
$scope.edit = function () {
$scope.editing = true;
// We control display through a class on the directive itself. See the CSS.
element.addClass( 'active' );
// And we must focus the element.
// `angular.element()` provides a chainable array, like jQuery so to access a native DOM function,
// we have to reference the first element in the array.
inputElement[0].focus();
};
// When we leave the input, we're done editing.
inputElement.prop( 'onblur', function() {
$scope.editing = false;
element.removeClass( 'active' );
});
}
};
});
app.controller('ContactsCtrl', function ( $scope ) {
$scope.contacts = [
{ number: '+25480989333', name: 'sharon'},
{ number: '+42079872232', name: 'steve'}
];
});