Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate Angularjs $scope variable in javascript?

mapApp.controller("myController", function ($scope,$http) {
            $scope.namePlaceHolder= "Name";
            $scope.name = "";
};

I bound a scope variable to an html input as follows.

<input id="foo" type="text" placeholder="{{namePlaceHolder}}" ng-model="name" value="{{name}}"/>

If a user types something in text box the $scope.name property changes. But when I change it using javascript the $scope.name data doesn't change.

on(document.getElementById("button"), "click", function (e) {
        document.getElementById("foo").value = "ascd...";
})

This code does not populate $scope.name data.

like image 378
barteloma Avatar asked Dec 04 '13 14:12

barteloma


People also ask

What is $scope in AngularJS?

$rootScope is a parent object of all “$scope” angular objects created in a webpage. $scope is a child object that is used to bind the HTML(view) & Javascript(Controller) in a webpage. It is created with the ng-app directive. It is created with the ng-controller directive.

What is $$ in AngularJS?

The $ in AngularJs is a built-in object.It contains application data and methods.

Is $scope still supported in angular2?

In Angular 2.0, there will be no $scope .

What is rootScope apply ()?

$scope.$apply() This function is used to execute an expression in Agular. The function expression is optional and you can directly use $apply(). This is used to run watcher for the entire scope. $rootScope.$digest()


2 Answers

Accesing scope from external element:

on(document.getElementById("button"), "click", function (e) {
            var scope = angular.element(document.getElementById("foo")).scope();
            scope.name = "hello, World!";
    })
like image 133
MeLight Avatar answered Nov 02 '22 08:11

MeLight


Accessing and apply scope from external element:

JS:

on(document.getElementById("button"), "click", function (e) {
            var scope = angular.element(document.getElementById("foo")).scope();
            scope.name = "hello, World!";
            scope.$apply();
    })
like image 7
Parth Patel Avatar answered Nov 02 '22 09:11

Parth Patel