0

Perhaps this is a poor way of doing this, so I'm open to changing this.

I am implementing a drag and drop function through a <drag-item> directive and a <drop-target> directive. The <drop-target> directive successfully calls this function in the parent scope:

$scope.testAddSet = function(){
    console.log($scope.workoutItem); // gives me the last value
    $scope.thisMonth[0].sets.push($scope.workoutItem);
    $scope.$apply(); // needed to update the view, but uses the old value for workoutItem "test"
}; 

$scope.workoutItem = "test"; // value declared here

but my <drag-item> directive doesn't seem to update the value of $scope.workoutItem,

View:

<div ng-repeat="exercise in exercises">
   <drag-item workout-item="workoutItem" exercise="exercise"></drag-item>
</div>

<drag-item> directive:

angular.module('app.directives.dragItem', [])
  .directive('dragItem', function(){
    return { 
      restrict: 'E',
      scope: {
        exercise: '=', 
        workoutItem: '='
      },
      templateUrl: "templates/dragTile.html",
      link: function(scope, element, attrs){
        element.on('dragstart', function (event) {
          scope.workoutItem = scope.exercise.name; //correctly updates the local scope, but not the parent scope
          console.log(scope.workoutItem); 
        });
      }
    };
  });

How do I fix this?

Nate May
  • 3,814
  • 7
  • 33
  • 86
  • 1
    `$scope.$apply()` inside event `dragstart` event will run digest & update will update binding correctly – Pankaj Parkar Feb 17 '16 at 19:18
  • @PankajParkar `$scope` wasn't recognised, and `scope.$apply()` didn't work. – Nate May Feb 17 '16 at 20:00
  • Ahhh !! Got it, its issue related to `ng-repeat`, do try `$parent.workoutItem` instead of `workoutItem` like ``, for more detail refer [this answer](http://stackoverflow.com/a/35465962/2435473) – Pankaj Parkar Feb 17 '16 at 20:31

1 Answers1

1

Looks like the problem is that you are defining $scope.workoutItem in your parent scope and then directive is creating another workoutItem property at directive's scope level. To avoid this, it is recomended that you use dots(.) to define your models. Please try something like:

$scope.workout = {item: undefined}

and then in your view:

<div ng-repeat="exercise in exercises">
   <drag-item workout-item="workout.item" exercise="exercise"></drag-item>
</div>

I think this should solve your problem without modifying the directive itself.

  • In addition I had to use `scope.$apply()` at the end of my 'dragstart' event function after the reassignment (@PankajParkar). – Nate May Feb 17 '16 at 21:08