angularjsangularjs-scopeangularjs-controllerangularjs-decorator

Returning scope from Controller in AngularJS


I want to bind the return value (always an object) of a Controller to the scope.

instead of:

$scope.test = "test"

like so:

return {
  test: "test"
}

so i can use it in my view like

{{ test }}

The reason i want to use this is because of my directives, services, etc. still working like this.

(function(module) {

  var SomeFactory = function SomeFactory(

  ) {

    var test = 2;

    var getTest = function getTest() {
      return test;
    }

    return {
      getTest : getTest
    }
  }

  module.factory('someFactory', [
    SomeFactory
  ])

})(angular.module('app'))

So my controller should be look like this:

(function(module) {

  var SomeController = function SomeController(
    $state
  ) {

    var loggedIn = true;

    var isLoggedIn = function isLoggedIn() {
      return loggedIn;
    }

    return {
      isLoggedIn : isLoggedIn
    }
  }

  module.controller('SomeController', [
    '$state',
    SomeController
  ])

})(angular.module('app'))

Someone can help.

An alternative solution like:

$scope.add({
  test: 2,
  do: function() {}
})

is also okay :)

Thanks for your help

EDIT: I want only returning an object {} and this object accessible over a decorator or something else


Solution

  • You can extend your scope in the controller the following way:

    angular
      .module("myModule", [])
      .controller("MyController", ["$scope", function($scope) {
          angular.extend(
              $scope,
              {
                  test: 2,
                  do: function() { return 3;}
              }
          );
      }]);
    

    and then use it like this

    <div ng-controller="MyController">
      {{test}}
      {{do()}}
    </div>
    

    Plunker with an example