如何在 AngularJS 中使用属性本身将可写参数传递给属性指令
How to pass a writable argument to an attribute directive using the attribute itself in AngularJS?
在编写属性指令时,我想将一个参数传递给指令,该指令是可以写入的属性路径。 (很像 ng-model 属性在输入上的工作方式。 如何设置指令以便可以写入它?
示例:以 AngularJS 网站上的 Draggable 指令为例。 只需在元素上声明属性即可使用它。
<span draggable>Drag ME</span>
我想创建一个新指令,如下所示:
<span draggable="somePath.someObj">Drag ME</span>
当在指令中监视事物时(例如元素的位置),值将被写入位于作用域上 somePath.someObj 的对象。
这是我从基本指令开始的:
angular.module('drag', []).
directive('draggable', function($document) {
return function(scope, element, attr) {
var startX = 0, startY = 0, x = 0, y = 0;
element.css({
position: 'relative',
border: '1px solid red',
backgroundColor: 'lightgrey',
cursor: 'pointer'
});
element.on('mousedown', function(event) {
// Prevent default dragging of selected content
event.preventDefault();
startX = event.screenX - x;
startY = event.screenY - y;
$document.on('mousemove', mousemove);
$document.on('mouseup', mouseup);
});
function mousemove(event) {
y = event.screenY - startY;
x = event.screenX - startX;
element.css({
top: y + 'px',
left: x + 'px'
});
}
function mouseup() {
$document.unbind('mousemove', mousemove);
$document.unbind('mouseup', mouseup);
}
}
});
(Plunkr可在网站上找到。 不确定实际链接是什么)
我创建了一个有效的CodePen示例,演示如何使用scope.$apply函数调用中的$parse服务来执行此操作。
相关网页:
<section class="text-center" ng-app="app" ng-controller="MainCtrl">
<a href="#" my-directive="user.name">Hover me</a><br>
Current value of 'user.name': {{user.name}}
</section>
相关代码:
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.user = {
name: 'value from controller'
};
});
app.directive('myDirective', function($parse) {
return {
link: function(scope, element, attrs) {
element.bind('mouseenter', function(event) {
scope.$apply(function() {
$parse(attrs.myDirective).assign(scope, 'value from directive');
});
});
}
};
});
您可以使用
$parse
服务,请参阅此处的示例文档:http://docs.angularjs.org/api/ng.$parse
相关文章:
- 函数未将值作为参数传递
- 如何将参数传递到angularJs中的工厂
- 如何在HTML元素上创建函数,而不是将元素作为参数传递
- JavaScript常量-作为参数传递或直接使用
- 如何将javascript对象作为参数传递到c#web服务中
- 将参数传递给函数
- 无法在 标记 SRC 属性中传递参数
- 将对象作为参数传递后的未定义属性
- 如何在 AngularJS 中使用属性本身将可写参数传递给属性指令
- 什么是将对象属性作为函数参数传递的良好策略/模式
- 将自定义javascript对象属性作为参数传递到要更新的函数中
- 我可以在 Vue.Js 中的计算属性中传递参数吗?
- 将对象属性作为函数参数传递
- 希望将属性的名称作为函数的参数传递.在Javascript
- 在onclick属性中传递一个JavaScript函数作为参数
- 将Doc属性作为参数传递到Mongodb上的函数中
- 通过if语句的函数参数传递对象属性
- 将输入属性数据传递给其他输入函数参数 - 角度
- 将属性作为参数传递,同时设置同一对象的其他属性
- Javascript将元素ID属性作为参数传递