2017-01-05 80 views
0

我正在嘗試從控制器中讀取ng-model,但是我無法使其工作。它說ng模型是未定義的。我試圖應用他人提供的解決方案來解決這個類似的問題,但我仍然無法完成工作。也許是因爲我錯了。AngularJS - ng-model在控制器中未定義

我有下面的代碼片段:

var app = angular.module('myApp', []); 
 
app.controller('myCtrl', function($scope) { 
 
    $scope.apply = function() { 
 
    $scope.name = {} 
 
    var firstName = $scope.name.FirstName; 
 
    alert(firstName); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
 

 
<div ng-app="myApp" ng-controller="myCtrl"> 
 
    <button ng-click="apply()" type="button">Apply</button> 
 
    Name: 
 
    <input ng-model="name.FirstName"> 
 
</div>

然而,警報說,變量「名字」點擊「應用」按鈕後不確定。所以我試着改用下面的代碼。

var app = angular.module('myApp', []); 
 
app.controller('myCtrl', function($scope) { 
 
    $scope.apply = function() { 
 

 
    var theFirstname = ""; 
 
    $scope.name = { 
 
     theFirstname: $scope.name.FirstName 
 
    } 
 

 
    alert(theFirstname); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
 

 
<div ng-app="myApp" ng-controller="myCtrl"> 
 
    <button ng-click="apply()" type="button">Apply</button> 
 
    Name: 
 
    <input ng-model="name.FirstName"> 
 
</div>

然而,這似乎是我無法分配$scope.name.FirstName變量 「theFirstname」。

回答

3

name的初始化移動到apply()以上。

通過這樣做,name.FirstName可以從模板中初始化爲name已經在範圍上定義。

在你的情況,$scope.name={}在處理程序中被定義,從而nameundefined通過當ng-model附連到文本框的時間。

var app = angular.module('myApp', []); 
 
app.controller('myCtrl', function($scope) { 
 
    // Define the `name` object 
 
    $scope.name = {}; 
 

 
    $scope.apply = function() { 
 
    var firstName = $scope.name.FirstName; 
 
    console.log(firstName); 
 
    }; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
 

 
<div ng-app="myApp" ng-controller="myCtrl"> 
 
    <button ng-click="apply()" type="button">Apply</button> 
 
    Name: 
 
    <input ng-model="name.FirstName"> 
 
</div>