tomersss2
tomersss2

Reputation: 155

angular.js - passing an object from directive to the view controller

*Please note: there is a Plunker link: https://plnkr.co/edit/PAINmQUHSjgPTkXoYAxf?p=preview

At first I wanted to pass an object as parameter on directive click event, (it was too complex for me), so i decide to simplify it by sending the event and the object separately.

In my program the object is always undefined in the view-controller and the view itself in oppose to the Plunker example.

In the Plunker example it's undefined on the controller only on the first passing event (the second directive click event works fine).

HTML

<pick-er get-obj-d="getObj()" obj-d="obj"></pick-er>

View-Controller

function mainController($scope)
{
    $scope.test = "work";
    $scope.getObj = function(){
        $scope.test = $scope.obj;
    }
}

Directive:

function PickerDirective()
{
    return {
        restrict: 'E',
        scope: // isolated scope
        {
            obj : '=objD',
            getObj: '&getObjD'
        }, 
        controller: DirectiveController,
        template:`<div ng-repeat="item in many">
                      <button ng-click="sendObj()">
                          Click on me to send Object {{item.num}}
                      </button>
                  </div>`
    };


    function DirectiveController($scope, $element)
    {
        $scope.many =[{"num":1,}];
        $scope.sendObj = function() {
            $scope.obj = {"a":1,"b":2, "c":3};
            $scope.getObj();
        } 
    }
}

Upvotes: 0

Views: 418

Answers (1)

Carlos Arauz
Carlos Arauz

Reputation: 805

I your case, will be more simple to use events, take a look at this Plunker:

https://plnkr.co/edit/bFYDfhTqaUo8xhzSz0qH?p=preview

Main controller

function mainController($scope)
{
console.log("mainCTRL ran")
$scope.test = "work";
  $scope.$on('newObj', function (event, obj) {
    $scope.obj = obj;
    $scope.test = obj;
  });
}

Directive controller

function DirectiveController($scope, $element)
    {
     $scope.many =[{"num":1,}]
        $scope.sendObj = function() {
          $scope.$emit('newObj', {"a":1,"b":2, "c":3} )
        }
    }

    return {
        restrict: 'E',
        controller: DirectiveController,
        template:'<div ng-repeat="item in many"><button ng-click="sendObj()">Click on me to send Object {{item.num}}</button></div>' 
    }

Upvotes: 2

Related Questions