AngularJS - Initialize form data based on value

350 Views Asked by At

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.

1

There are 1 best solutions below

2
On BEST ANSWER

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