0

属性ディレクティブを書くとき、書き込み可能なプロパティパスである引数をディレクティブに渡したいと思います。(ng-model 属性が入力に対してどのように機能するかによく似ています。) ディレクティブに書き込みできるようにするには、どのようにディレクティブを設定すればよいですか?

例: AngularJS Web サイトにある 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 は Web サイトにあります。実際のリンクが何であるかはわかりません)

4

2 に答える 2

0

scope.$apply関数呼び出し内で$parseサービスを使用してこれを行う方法を示す、動作する CodePen の例を作成しました。

関連する 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');
        });
      });
    }
  };
});
于 2013-10-03T17:09:34.517 に答える
0

このサービスを使用できます$parse。例を含むドキュメントを参照してください: http://docs.angularjs.org/api/ng.$parse

于 2013-10-03T16:55:40.690 に答える