by
845 17
1
5
8,486
1
Top 1% !
Pearl of Wisdom
Easy-to-find
Specified
OpenSource
Popularity: 566th place
Created
Modified Sep 20, 2016

Published on:

Frameworkangular.js
LanguageHTML
LanguageJavascript
LicenseMIT_X11

AngularJS 'Ctrl as vm' pattern

Within controller use 'var varname' if it is only needed internally, anything which needs to be bound to the ViewModel uses 'vm.varname' because in 'Controller as vm' pattern you forego using $scope to bind to the ViewModel and instead use the vm.object instead. Sometimes $scope is necessary but less so using this pattern....vm is readable and conveys meaning. Thanks John
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/1446373/AngularJS--Ctrl-as-vm--pattern?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
// AngularJS 'Controller As vm' pattern <script> (function(){ "use strict"; var app = angular.module('app') .controller('Customers', [function() { var vm = this; //this is implicitly bound to controller's scope vm.title = 'Customers'; vm.customers = [ {name: 'Haley'}, {name: 'Ella'}, {name: 'Landon'}, {name: 'John'} ]; }]) .controller('Shells', [function() { var vm = this; //this need not be named identically as in HTML vm.title = 'Shells'; vm.shells = [ {name: 'Main Shells'}, {name:'Half Shells'},{name: 'Quarter Shells'} ]; }]); })(); </script> <div ng-controller="Shell as shellVm"> <h1>{{ shellVm.title }}</h1> <article ng-controller="Customers as customersVm"> <h2> {{ customersVm.title }} in </h2> <ul ng-repeat="c in customersVm.customers"> <li>{{ c.name }}</li> </ul> </article> </div>
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus