Reputation:
I'm currently trying to understand a block of code that i found and there is part which gives me a hard time
I directive is declared that way :
(function () {
angular
.module('meanApp')
.directive('navigation', navigation);
function navigation () {
console.log("enters directive");
return {
restrict: 'EA',
templateUrl: '/common/directives/navigation/navigation.template.html',
controller: 'navigationCtrl as navvm'
};
}
})();
The controller:
(function () {
angular
.module('meanApp')
.controller('navigationCtrl', navigationCtrl);
navigationCtrl.$inject = ['$location','authentication'];
function navigationCtrl($location, authentication) {
console.log("enters navigation controller")
var vm = this;
vm.isLoggedIn = authentication.isLoggedIn();
vm.currentUser = authentication.currentUser();
}
})();
The view :
<div class="navbar navbar-default">
<div class="container">
<div id="navbar-main">
<ul class="nav navbar-nav">
<li><a href="/">Home</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li ng-hide="navvm.isLoggedIn"><a href="login">Sign in</a></li>
<li ng-show="navvm.isLoggedIn"><a href="profile">{{ navvm.currentUser.name }}</a></li>
</ul>
</div>
</div>
</div>
The thing i don't understand is the following:
Why do we use a 'nvvm' variable while the instance of the controller we work with in the controller is named 'vm'.
In the view, instead of navvm.currentUser.name
, i would have chosen to simply use vm.currentUser.name
Thanks for helping me to put some light on this detail
Upvotes: 1
Views: 78
Reputation: 22733
nvvm is the alias of controller name, so you can use nvvm in place of navigationCtrl.
vm is a variable inside the controller so not accessible from page.
Upvotes: 0
Reputation: 7605
As mentioned in the directive:
controller: 'navigationCtrl as navvm'
The navigationCtrl
can be referred using the navm
alias in your view, explaining the navvm.currentUser.name
.
If it bothers you that much, just replace the controller alias
by:
controller: 'navigationCtrl as vm'
And use it as you wanted: vm.currentUser.name
.
Note that this alias
allows you to bind data to your controller
using this
and thus get rid of the $scope
keyword.
Upvotes: 1