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

Having issues retrieving accurate data from a service in an AngularJS controller

I am currently facing some challenges with a service while trying to develop a mobile app using Ionic/Angular/Cordova. The code snippet in question is as follows: SERVICE: 'use strict'; angular.module('MyDemoApp.services').ser ...

Is there a way to use a single url in Angular for all routing purposes

My app's main page is accessed through this url: http://localhost:4200/ Every time the user clicks on a next button, a new screen is loaded with a different url pattern, examples of which are shown below: http://localhost:4200/screen/static/text/1/0 ...

Ways to conceal <td>s in angularjs on specific rows during ng-repeat

In the first <tr>, I have a table with many <td> elements that I am populating using ng-repeat. <tr ng-repeat="receipt in $data"> <td data-title="voucher number"> <span>{{receipt.voucher_no}}</span> </td ...

Transferring Data from JSON Object to an Array

In my AngularJS Controller, I have the following object: {"team":"1","name":"abc","age":"20"}, {"team":"1","name2":"def","age2":"21"}, {"team":"2","name":"ghi","age":"22"}, {"team":"2","name2":"jkl","age2":"23"}, I am looking to consolidate the items int ...

Leveraging Webpack for the exclusive creation of a vendor bundle

Presently, our AngularJS project relies on Bower for front-end dependencies and the bower-concat Grunt task to merge bower_components into a single libraries.js file. Similarly, we assemble library CSS files into a libraries.css. Looking ahead, we aim to ...

Prevent ng-click functionality from activating when clicking on a link inside an external element

I am facing an issue on my website using ui-router. I have a table with ng-click set on the cells, but there are links inside the cells as well. My goal is to disable the ng-click when the link is clicked. <div ng-click="click()" style="background: #d3 ...

Submitting the object in the correct format for the Firebase database

My goal is to structure the Firebase database in the following way: "thumbnails": { "72": "http://url.to.72px.thumbnail", "144": "http://url.to.144px.thumbnail" } However, I am struggling to correctly set the keys '72' and '144&apos ...

Retain the chosen choice even when the updated options list no longer includes that value

I am using a select element with ngOptions that is based on an array. The contents of this array may change dynamically. However, when the new array value does not include the selected option value, the selectController sets the option value to undefined. ...

Simulate a new Date object in Deno for testing purposes

Has anyone successfully implemented something similar to jest.spyOn(global, 'Date').mockImplementation(() => now); in Deno? I've searched through the Deno documentation for mock functionality available at this link, as well as explored t ...

Using the Angular Directive Method Binding for Selecting Items

Is it normal for all method bindings to fire when changing a select element with the same directive in Angular? For example, selecting a state also triggers the selection of a dog. Do I have a misunderstanding of Angular Directives? This behavior does not ...

The parameter cannot be assigned to type 'void' because it is of type 'Promise<unknown>'.ts(2345) - mockReturnValueOnce

Encountering an error while using the mockReturnValueOnce method, specifically 'Argument of type 'Promise' is not assignable to parameter of type 'void'.ts(2345)'. I attempted to solve it by writing the following code: .spyO ...

Having trouble importing moment-range into your Angular 4.x application using ES6? Getting an error about incompatible call signatures?

In my Angular 4.x application, I encountered an issue while trying to import the moment-range package. The official documentation suggests using the following code: import Moment from 'moment'; import { extendMoment } from 'moment-range&apo ...

Is it possible to bind to a service variable in a controller without using $scope and utilizing the

As I delve into the world of controllerAs syntax in AngularJS, I've encountered a snag when attempting to bind a service variable. The traditional approach using `$scope.$watch` or `$scope.$on` would require injecting `$scope`, which seems counterintu ...

Validation with zod is unsuccessful under certain conditions

I am facing an issue with my form that contains a radio button with three input fields inside it. The submit button is supposed to validate that only one of the input fields is correctly entered. Despite using refine() in zod validation, I cannot get it ...

React: Implement a feature to execute a function only after the user finishes typing

Currently, I am using react-select with an asynchronous create table and have integrated it into a Netsuite custom page. A issue I am facing is that I would like the getAsyncOptions function to only trigger when the user stops typing. The problem right now ...

Different ways to reference a variable in Typescript without relying on the keyword "this" throughout the codebase

Can we eliminate the need to write "this" repeatedly, and find a way to write heroes, myHero, lastone without using "this"? Similar to how it is done in common JavaScript. https://i.stack.imgur.com/TZ4sM.png ...

Circular dependency has been detected when using the ESLint with TypeORM

Having two entity typeorm with a bi-directional one-to-one relationship: Departament: @Entity('Departament') export default class Departament { @PrimaryGeneratedColumn() id: string; @Column() departament_name: string; @OneToOne(type ...

Why is my RxJS timer not waiting for the specified time?

I'm diving into the world of RxJS and trying to grasp its concepts. During some testing, I encountered a puzzling issue that has me stumped. Below is the snippet in question : let item = { id: 1, name: 'chair' }; const asyncItem = timer(20 ...

What is the process for retrieving input values in Angular JS?

When using Angular JS, inputs can be created. <input type="text"> <input type="text"> How can I retrieve values from each input and send them to the server? I attempted: <input type="text" ng-model="typeInput"> However, I am only abl ...

Error message stating: "Unable to read property 'then' as it is undefined within Angular nested promises."

I'm having trouble passing data back from a service to a controller in my AngularJS application. The service I am calling inside a factory makes an HTTP request for JSON data and then needs to modify it before returning it to the controller. However, ...