简体   繁体   中英

AngularJS : set parent controller $scope variable from child directive

I have a main controller EventCtrl that sets a formData variable on its scope.

This controller has a setEventObject method that overrides the formData object.

My purpose is to be able to call this method from child directives and apply the new variable value recursively to every scopes.

Here is the controller and its setEventObject function :

app.controller('EventCtrl', function($scope) {
  $scope.formData = {
    id: 1,
    name: 'tennis lesson'
  }
  $scope.events = [
    {id: 1, name: 'tennis lesson'}, 
    {id: 2, name: 'golf lesson'}, 
    {id: 3, name: 'handball lesson'}
  ];

  this.setEventObject = function(eventId) {
    angular.forEach($scope.events, function(elem) {
      if (elem.id == eventId) {
        $scope.formData = {
          id: elem.id,
          name: elem.name
        };
      }
    });
  }
});

Here is the associated Plunkr , on clicks on links, it should set the form input and reset the formData variable.

Thanks for helping !

You are using element.bind('click' to listen to click. This is jQuery, and these changes are outside angular world. You need to tell angular about your change.

replace eventCtrl.setEventObject(scope.event.id); line with

scope.$apply(function () {
    eventCtrl.setEventObject(scope.event.id);
});

I tried the above change in your plunker and it works as expected.

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