John Halbert
John Halbert

Reputation: 1350

Assign Scope Objects Outside of Angular App

I'm writing a small Angular app which relies on some common functions defined outside the app to do tasks across different controllers. In one of my controllers the scope object is declared when the controller is loaded. I'd like to be able to assign it later in one of my helper functions, but the assignment is not working.

Here's the relevant code:

.controller('myCtrl', function($scope, myFactory){

    $scope.myObj;

    $scope.saveEntry = function() {
        myFactory.saveEntry($scope.obj);
      formatSingleTableEntry($scope.obj, $scope.myObj);
      $scope.obj = {};
    }

  });

  // Entry Formatter
  function formatSingleTableEntry(entry, scopeObject) {
      if (typeof scopeObject === 'undefined') {
        scopeObject = [];
      }
      if (typeof entry.obsDt === 'string') {
          entry.obsDt = dateFormat(entry.obsDt);
      }
      scopeObject.push(entry);
    }

    // Date Formatter
    function dateFormat(date) {
      date = date.split('');
      date[10] = 'T';
      date = date.join('');
      return Date.parse(date);
    }

If I assign the scope object as an empty array in the controller, everything works, but assignment doesn't in this configuration. I can check to see that assignment actually happens in the helper function, but when I check in the controller it hasn't.

Why?

Upvotes: 0

Views: 40

Answers (1)

charlietfl
charlietfl

Reputation: 171689

One main problem is while undefined $scope.myObj; is a primitive. WHen you pass that as argument to function there is no reference back to the original variable

var foo;

function test(myVar){
    myVar = 'Some string';
    //   myVar != foo
}

test(foo);
console.log(foo)// undefined

If the original variable is an array or object you pass a reference to that array or object and can thus manipulate it.

In short, just declare $scope.myObj =[]; and don't reassign it and break any reference created

Upvotes: 1

Related Questions