AngularTS - Using $apply stops the controller from initializing

Every time I launch the application, the angular {{ }} tags remain visible. Removing $scope.$apply eliminates the braces and displays the correct value.

I am utilizing Angular with Typescript.

Controller:

module Application.Controllers {
export class TestController {

    public hello: string = "hello";

    private scope: any;

    constructor($scope: ng.IScope) {

        this.scope = $scope;
        this.scope.hello = "Hi";
        this.scope.$apply();

        alert('no errors');

    }

}

}

Controller Definition (in an initialization function a few seconds after the app loads):

var appController2 = AppModule.controller("TestCTRL", ["$scope", Application.Controllers.TestController]);

The view:

<div ng-controller="TestCTRL as t">
    <div>{{ t.hello }} {{ 1 - 1 }}</div>
</div>

Instead of seeing "Hello 0" I see {{ t.hello }} {{ 1 - 1 }}

If I remove the this.scope.$apply call, it works, but it shows hello instead of hi.

I am using IE 11, Angular 1.4.9

I also have 2 other functioning controllers in my DOM, and whenever it reaches this one, it halts unless I eliminate $scope.$apply

Answer №1

There are two instances of the word hello: one is a field within the controller with the value "hello", accessible in the view using {{ t.hello }}, and the other is a field within the scope with the value "hi", accessible in the view using {{ hello }}, or, if you have stored the scope within a field of the controller, then it can be accessed using {{ t.scope.hello }}.

If you prefer to use just one field, then utilize

this.hello = "Hi";

instead of

this.scope.hello = "Hi";

When utilizing controllerAs, it's typical not to store anything directly into the scope. In most cases, you may not even require the scope at all.

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

Applying Angular to Add a CSS Class

I am working with an Angular controller and have the following model on the scope: $scope.model = { subscriber: { email: '', name: '' }, notice: { text: '', type: '' } } My goal is to display a P tag when notic ...

The 3-way data binding in angularFire does not update a function

My issue involves a firebaseObject (MyFirebaseService.getCurrentUser()) being bound to $scope.user. Once successfully bound, I iterate through the object to check if it contains an "associatedCourseId" equal to a specific value ($stateParams.id). If it doe ...

AngularJS $scope changes not reflecting in the view

Struggling with a persistent issue in my angularJS $scope. I've been working on updating an array within a controller function, and even though the values are changing based on console logs, the view isn't reflecting those changes. Here's wh ...

Error happening outside of controllers or services but not being recorded

I've encountered an issue where exceptions occurring outside of controllers or services in plain JavaScript code are not being reported, do not appear in the console, and cannot be handled. For example, if there is an exception within a Car class that ...

Extract keys from a list of interface keys to create a sub-list based on the type of value

Issue Can the keys that map to a specified value type be extracted from a TypeScript interface treated as a map? For example, consider the WindowEventMap in lib.dom.d.ts... interface WindowEventMap extends GlobalEventHandlersEventMap, WindowEventHan ...

How to Insert <ul></ul> After Every Other <li> Element Using Angular's ngRepeat

With my current setup, I have a list item (li) within a list (ul) and applied ngRepeart. However, I would like to create a new ul after every 2nd li. Is this possible with AngularJS? <ul> <li>simth</li> <li>aryan</li> < ...

The data structure of '(string | undefined)[]' cannot be matched with type '[string | undefined]'

I've been working on a TypeScript project and I've encountered the ts(2322) error as my current challenge. Here's a snippet of my code: import { BASE_URL, AIRTABLE_BASE_ID, AIRTABLE_TABLE_STUDENT, AIRTABLE_TABLE_CLASSES, API_KEY, ...

The $mdSticky feature in AngularJS Material seems to be malfunctioning

It's been a challenge for me to get the md-toolbar to stay in the top position. I decided to create a custom directive using the $mdSticky service in AngularJS. var app=angular.module('app',['ngMaterial']); app.controller(&apos ...

The functionality of window.location.href seems to be malfunctioning on mobile devices within an ionic application

Attempting to open a view with a function call from the UI side <ion-option-button class="button-light icon ion-chatbubble" ng-click="openView('username')"></ion-option-button> The controller code for this action is as follows: $sc ...

I am seeking advice on how to create an extension for a generic class in TypeScript specifically as a getter

Recently, I discovered how to create extensions in TypeScript: interface Array<T> { lastIndex(): number } Array.prototype.lastIndex = function (): number { return this.length - 1 } Now, I want to figure out how to make a getter from it. For exam ...

The utilization of React.Component inheritance in TypeScript

In my attempt to develop a base class using React.Component and derive two classes from the base class, I have encountered an issue. Here is how I structured the classes: interface BaseItemProps { base_prop: string; } class BaseItem<P, T> exten ...

Encountering an issue with MUI 5 where it is unable to access properties of undefined when utilizing makestyles

I recently finished building a react app using MUI-5 and everything was running smoothly. However, I've encountered a strange issue where my app refuses to start and I'm bombarded with multiple MUI errors. These errors started popping up after I ...

Issue: The last loader (./node_modules/awesome-typescript-loader/dist/entry.js) failed to provide a Buffer or String

This issue arises during the dockerhub build process in the dockerfile. Error: The final loader (./node_modules/awesome-typescript-loader/dist/entry.js) did not return a Buffer or String. I have explored various solutions online, but none of them have pr ...

What is the easiest way to compile a single .ts file in my src folder? I can achieve this by configuring the tsconfig.js file and running the yarn

{ "compilerOptions": { "target": "es5", "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLibCheck": true, ...

Both the maxlenght and ng-maxlength directives appear to be ineffective in AngularJS

In my HTML file, I have the following input: <input name="password" id="newPasswordConfirmation" ng-model="newPasswordConfirmation" type="number" inputmode="numeric" placeholder="" required ...

Converting a nested JSON object into a specific structure using TypeScript

In the process of developing a React app with TypeScript, I encountered a challenging task involving formatting a complex nested JSON object into a specific structure. const data = { "aaa": { "aa": { "xxx&qu ...

Images with spaces in their names are failing to load in React Native

I am currently trying to utilize an image within my react native application. At this point, my code is very minimal. The following code snippet is all I have for now: import React from 'react'; import { ScrollView, View, Text } from 'reac ...

Backend not receiving the request

While all tests pass successfully in Postman, I'm encountering an issue where requests are not reaching the backend when testing from the front-end. import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common ...

Angular 6: TypeError - The function you are trying to use is not recognized as a valid function, even though it should be

I'm currently facing a puzzling issue where I'm encountering the ERROR TypeError: "_this.device.addKeysToObj is not a function". Despite having implemented the function, I can't figure out why it's not functioning properly or callable. ...

Error encountered in Ionic app: array.push() is not a valid function

A situation arose in my application where I have a controller and factory set up. Inside the factory, there is an array that should hold IDs of certain elements. However, when attempting to push an element into the array, an error is triggered stating: ...