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

3
  • 2
    This may help you to understand the syntax- AngularJs “controller as” syntax - clarification? Commented Oct 13, 2016 at 10:05
  • I edited my question. It is not a duplicate. Commented Oct 13, 2016 at 10:23
  • please read this doc-Understanding Controllers. Especially this point may be helpful for you: Share code or state across controllers — Use angular services instead. Commented Oct 13, 2016 at 10:42

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

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>

1 Comment

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"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.