1

I am trying to add edit functionality to my app. In one view, I have a button that brings you to the edit page.

<button ng-click="editMission(selectedMission.key)">Edit Mission</button> 

The value selectedMission.key is used to determine what to initialize the edit page's form data with.

In the controller the function looks like this:

  $scope.editMission = function(key){
    $location.path('/edit');
  }

On the edit page I have:

<div data-ng-init="editInit()">

And in my controller I have:

      $scope.editInit = function(){
        var query = myDataRef.orderByKey();
        query.on("child_added", function(missionSnapshot){
          if (missionSnapshot.key()==key){
           ...
          }
        });    
      } 

How can I run the initialize function based on the key value from editMission. Should I use some getter/setter approach with a global key variable? I tried just placing the editInit code in editMission but the form data does not populate on view load.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
user3646037
  • 293
  • 1
  • 6
  • 16

1 Answers1

0

Common practice is to use a service to share variables between views/controllers.

So in your case you would use the getter/setter approach as you suspected. I don't know what exactly you're trying to do, but the service in your case would look something like this:

app.factory('missionKeyService', function() {

    var currentMission= {};            

    return {

        setMissionKey: function(missionKey) {
            currentMission.key = missionKey;
        },

        getMissionKey: function() {
            return currentMission.key;
        }
    }
})

And in your controller1:

//include 'missionKeyService' in your controller function params 
$scope.editMission = function(key) {
    missionKeyService.setMissionKey(key);
    $location.path('/edit');
}

And controller2:

//include 'missionKeyService' in your controller function params
$scope.editInit = function() {
       var currentKey = missionKeyService.getMissionKey();
       //do something with this key
       ...
}
LJ.Wizard
  • 605
  • 1
  • 6
  • 10
  • You are just missing one closed curly bracket to close the return – user3646037 Feb 21 '16 at 20:28
  • Sorry yeah, was coding on here on the fly. Edited my answer. Also removed the extra bracket bits in `controller2` (doesn't apply to he `editInit ` function). – LJ.Wizard Feb 21 '16 at 20:38