Optimal approach for incorporating controller As with UI Router

Currently working on a small search application using AngularJS and Elasticsearch. I am in the process of transitioning the app from using $scope to controller As syntax. I have implemented UI Router for managing routes/states. I have been attempting to use

controller: 'HomeCtrl',
controllerAs: 'home'

in my state declarations, and then using var vm = this; in the controller to bind to the scope.

I changed ng-model="searchTerms" on my search input to ng-model="home.searchTerms" and updated all necessary bindings. However, none of it seems to be functioning correctly?

Should I instead use ng-controller="HomeCtrl as home" in a parent div? Is this considered best practice? Will it work smoothly with UI Router?

UPDATE I have now added

var vm = this;
vm.searchTerms = searchTerms;

But despite these changes, I am still encountering an error in the Chrome console:

Uncaught ReferenceError: searchTerms is not defined(…)

UPDATED CONTROLLER

'use strict';

angular.module("searchApp.autocomplete", [])
  .controller('HomeCtrl', ['$sce', '$state', '$stateParams', 'searchService', function($sce, $state, $stateParams, searchService) {

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

      vm.noResults = false;
      vm.isSearching = false;

    vm.results = {
      searchTerms: null,
      documentCount: null,
      documents: [],
      queryTime : null,
      searchTermGrams: null,
      itemsPerPage: 10,
      maxResults: 100
    };

      //autocomplete
    vm.autocomplete = {
        suggestions: [],
        corrections: []
    };
    vm.showAutocomplete = false;

Answer №1

controller: 'HomeCtrl as home' is compatible with ui-router functionality.

UPDATE:

It is important to define and initialize any objects/variables before or while assigning them to vm. In the provided code snippet, the variable searchTerms is declared but not initialized. Below are some suggestions on how to address this issue assuming searchTerms is a string:

var searchTerms = '';

var vm = this;
vm.searchTerms = searchTerms;

Alternatively, you can only initialize if the variable is undefined:

var searchTerms = searchTerms || '';

var vm = this;
vm.searchTerms = searchTerms;

If you do not require a separate internal variable, you can directly initialize vm.searchTerms (although this method may not be preferred in most cases):

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

When working with Angular code, it is advisable to only expose necessary data to the view and keep the rest within the controller (or service/factory). For more guidance on best practices in Angular development, refer to John Papa's Angular Style Guide.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Anticipated request for spy navigation with path '/members' was expected, but unfortunately was not triggered

I am facing an issue with a service method that performs an HTTP delete operation. The expected behavior is that upon successful deletion, the page should be redirected to another location. However, during testing, I noticed that the router navigation func ...

Activate the content when selected

Is it possible for you to create a scenario where selecting one item makes other content active or visible, like on the Apple iPhone webpage? For example, when you choose the color of the iPhone 4, the model version becomes fully visible and interactive. ...

Develop a pair of jQuery plugins that are able to communicate with one another

My mind is currently in disarray. I am interested in developing two unique jQuery plugins: A tab plugin A slider plugin. These plugins need to be able to communicate with each other. For example, clicking on a tab should activate the corresponding index ...

Is it possible for me to verify the login status of an Auth0 user within my custom NextJS _app.js file?

Currently working on a NextJS application with nextjs-auth0 for authentication, which is completely new to me. I followed the documentation's suggestion and wrapped my _app.js with UserProvider, also using getInitialProps to set a global online/offlin ...

Tips for creating a personalized callback within a user function using JavaScript

Utilizing callbacks is a common practice when working with third-party libraries like jQuery. However, I have encountered a situation where I need to implement my own callback function. Consider the following snippet from my current code: // Get All Rates ...

Using data across multiple instances in node.js EJS partials

I need some advice regarding my nodejs project. I have created a sidebar partial that requires user data to be displayed on it. This sidebar is utilized across multiple pages in the project. However, currently, I have to include the user data in every func ...

In my coding project using Angular and Typescript, I am currently faced with the task of searching for a particular value within

I am facing an issue where I need to locate a value within an array of arrays, but the .find method is returning undefined. import { Component, OnInit } from '@angular/core'; import * as XLSX from 'xlsx'; import { ExcelSheetsService } f ...

at" symbol used as a parameter indicator in defining resources

According to the information provided in the documentation (http://docs.angularjs.org/api/ngResource.$resource): The syntax for using $resource is as follows: $resource(url[, paramDefaults][, actions]); The optional parameter paramDefaults represents the ...

Learn the art of generating multiple dynamic functions with return values and executing them concurrently

I am currently working on a project where I need to dynamically create multiple functions and run them in parallel. My starting point is an array that contains several strings, each of which will be used as input for the functions. The number of functions ...

Creating an array of logos in ReactJS with the help of TailwindCSS

After seeing multiple implementations of this feature, I find myself struggling to search for a solution. I can only access the HTML and CSS through inspecting elements, wondering if others are facing the same issue as me. Typically, we aim to implement t ...

Issue encountered when attempting to add multiple JavaScript functions through Greasemonkey using unsafeWindow

One issue that arises is that the functions are unable to recognize each other. For example: unsafeWindow.helloworld = function() { alert('Hello world!'); helloworld2(); // this fails with an error indicating it does not exist } unsa ...

Is it possible to repeat this action by swiping to the left?

I'm currently developing an app in PhoneGap and retrieving information using JSON. My goal is to trigger this function again with Ajax when I slide left. This is the code I have so far. Thank you to everyone for your assistance. $(document).ready( ...

Leveraging mongo aggregate functionality within the meteor framework to calculate the total number of unlocked and locked

So, I have a collection where I store documents related to users with a structure like: {_id: "hofjew233332j4", userId: "fhewojfw34324", achievementUnlocked: true }; My goal is to use the aggregate and underscore functions to group the documents by user ...

retrieving particular information from within a Firebase array

My Firebase document contains a list with various properties such as name and imgUrl. Currently, I am facing an issue with extracting only the "name:" information from the list in Firebase Cloud Firestore so that I can determine how many times a specific n ...

Keeping an eye on local storage with the help of AngularJS

I've implemented a module known as ngStorage to manage local storage operations. You can check it out here: (https://github.com/gsklee/ngStorage). Let's say I store an object in local storage using $localStorage.something = true; How can I monito ...

Make sure to concentrate on the input field when the DIV element is clicked

In my React project, I am working on focusing on an input element when specific buttons or elements are clicked. It is important for me to be able to switch focus multiple times after rendering. For instance, if a name button is clicked, the input box for ...

Rotating camera independently from its parent in Three.js

I have a scenario where an Entity is traversing a CatmullRomCurve3 path, moving left with the left or down arrow keys and right with the right or up arrow keys. Initially, I encountered an issue where I wanted the Entity to face perpendicular to the path ...

Stop ajax loading animation for a specific scenario

I usually have a global ajax load animation that runs during every ajax call. However, there are certain cases where I need to disable this effect. How can I achieve that? This is the code for the global animation : $(document).ajaxStart(function(){ $ ...

Why does the AngularJS ngRepeat filter permanently remove null values?

Check out this JSFiddle demonstration I created to illustrate the problem: http://jsfiddle.net/s6Lj2/2/ Observe that in the dataset $scope.places = [{ name: 'Chicago', status: 'Active', analyst: 'Sam', recor ...

What could be causing the "Cannot POST /api/" error to occur when attempting to submit a form?

Having issues with my basic website and struggling to find a solution. As a complete beginner in this field, I am stuck and need some guidance. Accessing http://localhost:3000/class/create works perfectly fine when running the server. However, trying to a ...