2014-09-27 89 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/

相關問題