2014-09-27 46 views
0

我想能够访问此控制器的功能内的控制器变量。如何访问控制器功能中的变量?

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

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

删除$范围 - 见下文和updated fiddle

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

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

更新小提琴:http://jsfiddle.net/y6cbeb34/1/ – jacob 2014-09-27 16:14:54

0

您可以尝试另一种方法:

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

上看到的jsfiddle:

http://jsfiddle.net/qn47syd2/

相关问题