0

I'd like to be able to access a controller variable inside a function of this controller.

Why is the following code throwing an error into the console instead of showing the input value ?

JS:

var app = angular.module("app", []);

app.controller("TestCtrl", function($scope) {
    $scope.string = "";

    $scope.click = function() { // I've also tried with $scope in parameter
        console.debug(string); // and $scope.string here, same issue
    }
});

HTML :

<div ng-app="app" ng-controller="TestCtrl">
    <input type="text" ng-model="string"></input>
    <button ng-click="click()">Click me !</button>
</div>

JSFiddle

0

2 Answers 2

2

remove $scope from the argument in you click function, and use it inside the function - see below and updated fiddle

app.controller("TestCtrl", function($scope) {
    $scope.string = "";

    $scope.click = function() {
        console.debug($scope.string);
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

You can try another approach:

app.controller("TestCtrl", function($scope) {
    this.string = "";
    var that = this;
    $scope.click = function() {
        console.debug(that.string);
    }
});

See on JSFiddle:

http://jsfiddle.net/qn47syd2/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.