我正在学习Angular我做了这个并且它工作正常,很简单:
<span>Your Name:</span><h1>{{Name.first+' '+Name.second}}</h1>
<script>
var app = angular.module('myApp', []);
app.controller('myController', function ($scope) {
$scope.Name = { first: 'First', second: 'Second' };
})
</script>
但我希望控制器从文本输入中读取值,所以我做了这个:
<p>First Name: <input type="text" ng-model="fName" /></p>
<p>Last Name: <input type="text" ng-model="lName" /></p>
<span>Your Name:</span><h1>{{Name.first+' '+Name.second}}</h1>
<script>
var app = angular.module('myApp', []);
app.controller('myController', function ($scope) {
$scope.Name = { first: $scope.fName, second: $scope.sName };
});
</script>
但它不起作用,我初学者足以确定我做错了
答案 0 :(得分:1)
它应该是lName,而不是sName:
$scope.Name = { first: $scope.fName, second: $scope.lName };
答案 1 :(得分:1)
这应该有所帮助:
<p>First Name: <input type="text" ng-model="Name.first" /></p>
<p>Last Name: <input type="text" ng-model="Name.second" /></p>
<span>Your Name:</span><h1>{{Name.first+' '+Name.second}}</h1>
<script>
var app = angular.module('myApp', []);
app.controller('myController', function ($scope) {
console.log("Loaded");
})
</script>
答案 2 :(得分:1)
您必须使用某个事件来更新$ scope.Name对象当您将$ scope.name显示为输出时。
目前我使用过ng-change你也可以使用ng-click等。根据要求
var app = angular.module('myApp', []);
app.controller('myController', function ($scope) {
$scope.getName=function(){
$scope.Name = { first: $scope.fName, second: $scope.lName };
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
<p>First Name: <input type="text" ng-change="getName()" ng-model="fName" /></p>
<p>Last Name: <input type="text" ng-change="getName()" ng-model="lName" /></p>
<span>Your Name:</span><h1>{{Name.first+ " " +Name.second}}</h1>
</div>
答案 3 :(得分:-1)
你的ng-model值应该是这样的
<p>First Name: <input type="text" ng-model="Name.fName" /></p>
<p>Last Name: <input type="text" ng-model="Name.lName" /></p>
这样对象hireachy维持两个绑定将起作用