0

How to programatically get the name from an alias of a AngularJS controllerAs syntax?

MyController as mine

How I get the mine variable? To be clear, I have MyController with multiple usages:

MyController as use1
MyController as use2

How inside MyController I get the use1 or the use2

Lucas Freitas
  • 194
  • 12
  • 2
    This may help you to understand the syntax- [AngularJs “controller as” syntax - clarification?](http://stackoverflow.com/questions/21287794/angularjs-controller-as-syntax-clarification) – Khalid Hussain Oct 13 '16 at 10:05
  • I edited my question. It is not a duplicate. – Lucas Freitas Oct 13 '16 at 10:23
  • please read this doc-[Understanding Controllers](https://docs.angularjs.org/guide/controller). Especially this point may be helpful for you: _**Share code or state across controllers — Use angular services instead.**_ – Khalid Hussain Oct 13 '16 at 10:42

2 Answers2

2

Here is how to use it

var app = angular.module("myShoppingList", []); 
app.controller("myCtrl", function($scope) {
    var mine = this; //You can change "mine" with whatever you want
    mine.products = ["Milk", "Bread", "Cheese"];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myShoppingList" ng-controller="myCtrl as mine"> <!--Use the choosen name-->
    <ul>
        <li ng-repeat="x in mine.products">{{x}}</li>
    </ul>
</div>
Weedoze
  • 13,683
  • 1
  • 33
  • 63
1

An example of "Controller As" syntax that was revealed in Angular JS 1.2.0

angular.module('app')
    .controller('Customers', [function() {
      var vm = this;
      vm.title = 'Customers';
      vm.customers = [
        {name: 'Haley'}, {name: 'Ella'}, {name: 'Landon'}, {name: 'John'}
        ];
}]);

To use it in view

<article ng-controller="Customers as vm">
   <ul ng-repeat="c in vm.customers">
       <li></li>
</ul>
</article>
Navoneel Talukdar
  • 4,393
  • 5
  • 21
  • 42
  • Thanks for your answer, I'm using exactly as you described. But there's any way I can get the name of the alias? Like inside the CustomerCtrl I can get "vm" (because vm is defined as the alias). I have a controller reused with different names and I would like to get the as "name" – Lucas Freitas Oct 13 '16 at 10:21