如何访问控制器函数中的变量?

时间:2014-09-27 16:08:54

标签: angularjs angularjs-scope

我希望能够访问该控制器函数内的控制器变量。

为什么以下代码会向控制台抛出错误而不是显示输入值?

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

2 个答案:

答案 0 :(得分:2)

从click函数中的参数中删除$ scope,并在函数内部使用它 - 见下文和updated fiddle

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

    $scope.click = function() {
        console.debug($scope.string);
    }
});

答案 1 :(得分:0)

您可以尝试其他方法:

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

参见JSFiddle:

http://jsfiddle.net/qn47syd2/