title: Cannot read property 'drag' of undefined D3
body: <p>I am beginner with D3 and I am trying to drag with mouse a rectangle but actually I experience some troubles.</p>
  
  <p>If I define var drag before to call it get this error: Cannot read property 'drag' of undefined</p>
  
  <p>If I define var drag after calling it, I get a different error: Cannot read property 'apply' of undefined
  But actually, searching on stackoverflow I read that to solve this probl I need to define the var drag before to call it and I am on a loop.</p>
  
  <p>Below you can see my code. Thanks in advance.</p>
  
  <pre><code>$(document).ready(function() {
  var width = 500;
  var height = 500;
  var fullAngle = 2 * Math.PI;
  var arc2 = d3.arc()
              .innerRadius(195)
              .outerRadius(200)
              .startAngle(0.18)
              .endAngle(fullAngle / 1.02);
  
  var svgContainer = d3.select("#container")
      .append("svg")
      .attr("width", width)
      .attr("height", height)
      .style("border", "1px solid");
  
  var group1 = svgContainer.append("g");
  var group2 = svgContainer.append("g");
  group2.append("path")
      .attr("d", arc2())
      .attr("fill", "blue")
  
  group1.attr("transform", "translate(" + 200 + "," + 200 + ")");
  group2.attr("transform", "translate(" + 250 + "," + 250 + ")");
  
  var rectangle = svgContainer.append("rect")
            .attr("x", 150)
            .attr("y", 50)
            .attr("width", 30)
            .attr('class', 'rectangle')
            .attr("height", 70)
            .call(drag)
  
      var drag = d3.behavior.drag().on('drag', function () {
          var obj = svgContainer.append("rect")
          dragMove(this, obj, 'rect')
      });
  });
  
  
  
      function setPoints(obj, prop) {
          obj[prop] = []
          var k = 0
          d3.selectAll('.rect')
              .each(function() {
                  var c = d3.select(this)
                  var cX = d3.transform(c.attr('transform')).translate[0]
                  var cY = d3.transform(c.attr('transform')).translate[1]
                  obj[prop].push({
                      x: cX,
                      y: cY,
                      index: k++
                  })
              })
      }
  
        function dragMove(rectangle, obj, prop) {
            var x = d3.event.x
            var y = d3.event.y
            setPoints(obj, prop)
            d3.select(rectangle).attr('transform', 'translate(' + x + ',' + y + ')')
            $scope.$apply()
        }
  </code></pre>