简体   繁体   中英

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).

  • I don't know why I get 2 different results in the simple Plunker simulation and my massive code, I hope both cases are 2 different results of the same logic issue.
  • A solution with passing an object as parameter from directive by event function will be welcome as well.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM