Javascript 如何在控制器中获取ng模型参数
我试图将最初在控制器中设置的ng模型参数绑定回控制器 我有类似的东西Javascript 如何在控制器中获取ng模型参数,javascript,angularjs,ionic-framework,Javascript,Angularjs,Ionic Framework,我试图将最初在控制器中设置的ng模型参数绑定回控制器 我有类似的东西 <div ng-app="myApp" ng-controller="personCtrl"> First Name: <input type="text" ng-model="firstName"><br> Last Name: <input type="text" ng-model="lastName"><br> <
<div ng-app="myApp" ng-controller="personCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.firstName = "Leo";
$scope.lastName = "Messi";
});
</script>
名字:
姓氏:
var-app=angular.module('myApp',[]);
应用控制器('personCtrl',功能($scope){
$scope.firstName=“Leo”;
$scope.lastName=“梅西”;
});
我试图在我的控制器中实现一个PUT方法,所以我需要将新值绑定回控制器。我试过了
<div ng-app="myApp" ng-controller="personCtrl">
<form>
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<button ng-click="UpdateProfile()"> Update </button>
</form>
</div>
名字:
姓氏:
更新
然后在中,我将控制器更新为
<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.firstName = "Leo";
$scope.lastName = "Messi";
$scope.UpdateProfile = function()
{
$scope.newFirstName = firstName
}
});
</script>
var-app=angular.module('myApp',[]);
应用控制器('personCtrl',功能($scope){
$scope.firstName=“Leo”;
$scope.lastName=“梅西”;
$scope.UpdateProfile=function()
{
$scope.newFirstName=firstName
}
});
但我有一个错误,说firstName不是define
任何帮助都将不胜感激它应该是:
$scope.UpdateProfile = function()
{
$scope.newFirstName = $scope.firstName;
}
});
您已经通过填充一些值预定义了作用域。作用域识别自己更新的值 按如下方式更新代码:-
$scope.newFirstName = $scope.firstName;
$scope.newLastName = $scope.lastName;
-可以为您提供更多信息,以便更好地理解 您的代码-您已将firstName附加到$scope变量,该变量是内部对象,firstName是其属性 例如,如果我使用testController创建一个示例testApp模块,并将属性test1附加到该模块上,然后控制台记录$scope变量。 然后我可以在控制台中看到整个$scope对象。 //代码在这里
var app =angular.module('testApp',[]);
app.controller('testController',testController);
testController.$inject=['$scope'];
function testController($scope){
$scope.test1="plunkr";
console.log($scope);
}
因此,您应该将firstName作为$scope对象的属性访问,而不是作为变量firstName访问
所以你的代码应该是
$scope.firstName = "Leo";
$scope.UpdateProfile = function()
{
$scope.newFirstName = $scope.firstName
}
});
或者,您可以进行一些更改以使自己的版本正常运行。
在控制器中:
$scope.UpdateProfile = function(firstName)
{
$scope.newFirstName = firstName
}
<button ng-click="UpdateProfile(firstName)"> Update </button>
在HTML中:
$scope.UpdateProfile = function(firstName)
{
$scope.newFirstName = firstName
}
<button ng-click="UpdateProfile(firstName)"> Update </button>
更新
@N.V.Prasad,将此
指的是那
?@kplus,所有范围变量都是双向数据绑定。因此,您可以简单地从$scope.firstName
本身获取firstName
的最新值。它不起作用,它给出了初始名称,而不是新名称$scope.newFirstName=$scope.firstName
。请阅读