Skip to content Skip to sidebar Skip to footer

Best Practice Way To Implement Contoller As Using Ui Router

Have a small search app using AngularJS and Elasticsearch. Trying to convert my the app from using $scope to controller As syntax. I'm using UI Router for my routes/states. Been tr

Solution 1:

controller: 'HomeCtrl as home' will work with ui-router. EDIT: You also need to define and initialize any objects/variables before or while assigning them to vm. In your updated code, you have defined searchTerms but it is not initialized. Please see the following for possible ways to rectify this assuming searchTerms is a string.

var searchTerms = '';

var vm = this;
vm.searchTerms = searchTerms;

or depending on your usage needs, you can only initialize if it is undefined:

var searchTerms = searchTerms || '';

var vm = this;
vm.searchTerms = searchTerms;

or if you don't need to have a separate internal variable, you can init vm.searchTerms directly (however in most cases I personally do not prefer this method):

var vm = this;
vm.searchTerms = '';

Regarding the rest of the posted code, you should generally expose to your view only what you need to access from there and keep the rest contained within your controller (or service/factory, etc.). So far I have yet to come across a solid, singular set of best practices for angular, however a great place to start is John Papa's Angular Style Guide.

Post a Comment for "Best Practice Way To Implement Contoller As Using Ui Router"