【问题标题】:How to pass a writable argument to an attribute directive using the attribute itself in AngularJS?如何使用AngularJS中的属性本身将可写参数传递给属性指令?
【发布时间】:2013-10-03 16:39:25
【问题描述】:

在编写属性指令时,我想将一个参数传递给该指令,这是一个可以写入的属性路径。 (很像 ng-model 属性在输入上的工作方式。)如何设置指令以便可以写入?

示例:以 AngularJS website 上的 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 在网站上找到。不确定实际链接是什么)

【问题讨论】:

  • 要链接到东西只需粘贴链接或[url goes here](text to display)
  • 到目前为止,您能提供您的指令的代码吗?但很可能您需要在指令中使用链接功能
  • @caffinatedmonkey 谢谢,但我的问题是找到我想要链接的 Plunkr 的实际链接,而不是如何链接到它

标签: javascript angularjs angularjs-directive


【解决方案1】:

我创建了一个working CodePen example 来演示如何在scope.$apply 函数调用中使用$parse 服务来做到这一点。

相关 HTML:

<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');
        });
      });
    }
  };
});

【讨论】:

    【解决方案2】:

    您可以使用$parse 服务,请参阅此处的示例文档:http://docs.angularjs.org/api/ng.$parse

    【讨论】:

      猜你喜欢
      • 2014-10-18
      • 1970-01-01
      • 2013-04-23
      • 2015-10-27
      • 2012-06-26
      • 1970-01-01
      • 2013-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多