2014-01-27 47 views
-1

未定義的錯誤嘗試初始化文本輸入框供用戶輸入,但得到的錯誤。 $ scope可以在取消註釋時設置intext。我已經解決這個砍死(排序的),但我失去了一些東西基本如常。angularjs - 從輸入文本字段

控制檯錯誤啓動:「錯誤:$ scope.intext未定義」除非我分配一個值。輸入框專門用於用戶輸入。也注意到我可以指定「爲什麼」,直到我試圖分裂沒有得到錯誤。

angular.module('myApp', []) 
    .controller('TextScreen', ['$scope', function($scope) { 
     //$scope.intext = "what"; 
     var why = $scope.intext.split('-'); 
}]); 

HTML

<div id="cont" ng-app="myApp"> 
<div ng-controller="TextScreen"> 
    <input type="text" ng-model="intext" /> 
</div> 
</div> 
+0

你想要做這樣的事情:http://jsfiddle.net/JFX23/? –

回答

1

的原因是$scope.intext是不確定的。 intext

目前還不清楚你正在嘗試做什麼,但我會建議初始化intext或將你的代碼移動到一個函數。就像這樣:

$scope.change = function() { 
    var why = $scope.intext.split('-'); 
}; 

HTML

<input type="text" ng-model="intext" ng-change="change()" /> 

像角文檔在這裏建議:

http://docs.angularjs.org/api/ng.directive:ngChange

,或者嘗試使用ng-init

ng-init="intext= 'demo'" 

樣品

<input type="text" ng-model="intext" ng-init="intext= 'demo'" /> 

Ø

+0

感謝您回覆! NG-變化立即根據該文檔,以便用於用戶輸入的計算結果不會與每個字符觸發?我通過初始化變量來入侵它。我需要像onchange這樣的文本字符串在用戶點擊後進行評估。我覺得自己應該留下的jQuery /本地免費至少要等到我的理解角度的方式的JavaScript。 – openquestions

1

var why = $scope.intext.split('-'); 

被立即處理,但在那一刻,$scope.intext是不確定的,所以你不能調用它.split

如果你想作用於用戶輸入的值,你應該把手錶上

$scope.$watch('intext', function(oldvalue, newvalue){ 
    if(angular.isDefined(newvalue) && newvalue != oldvalue) //ensuring undefined should not processed 
    var why = newvalue.split('-'); 
});