barteloma
barteloma

Reputation: 6845

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.

Upvotes: 5

Views: 16603

Answers (4)

Parth Patel
Parth Patel

Reputation: 71

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();
    })

Upvotes: 7

fdomig
fdomig

Reputation: 4457

Beside multiple other things. Here Prototypal Inheritance kicks in, which does overwrite your namePlaceholder property on the $scope object since your <form ...> does create a new $scope which inherits from your controller. Therefore you should always "use a dot".

E.g.

$scope.placeHolders = {
    name: "something"
};

and then

<input placeholder="{{placeholders.name}}">

Another thing is that you "left" the angular word when manipulating an angular variable outside of angular and therefore have to call angular.element(document.getElementById("foo")).scope().$apply(...) to "get back" in the angular world from your own JS.

But the better solution

mapApp.controller("myController", function ($scope,$http) {
    $scope.placeHolders = {
        name: 'Name'
    };
    $scope.selected = {
        name: ''
    };
    $scope.click = function() {
       $scope.selected.name = "something ...";
    };
};

<input ng-model="selected.name" placeholder="{{ placeHolders.name }}" ...>
<button ng-click="click()"></button>

Upvotes: 4

MeLight
MeLight

Reputation: 5555

Accesing scope from external element:

on(document.getElementById("button"), "click", function (e) {
            var scope = angular.element(document.getElementById("foo")).scope();
            scope.name = "hello, World!";
    })

Upvotes: 12

tymeJV
tymeJV

Reputation: 104775

DOM manipulations from within Angular should always come from directives - this allows for clean separation of code. In your case, you would never change the value attribute of that input, you would modify the ng-model so the changes will be reflected in your $scope variable.

So, in your above element of ID button, use an ng-click

ng-click="changeValue()"

//In controller
$scope.changeValue = function() {
    $scope.name = "ascd...";
}

Upvotes: 3

Related Questions