我试图通过我的案例中的ng-model获取用户输入值
我有
<div ng-controller="test">
<input type="input" ng-model="title"/>
<button type="button" ng-click="save()">Save</button>
</div>
JS
app.controller('test', function ($scope) {
$scope.save = function() {
console.log($scope.title) -> undefined.....
}
})
我不确定为什么$scope.title
是undefined
。我想得到输入值。任何人都可以帮我吗?非常感谢!
答案 0 :(得分:0)
您应该在控制器加载时初始化范围变量:
app.controller('test', function ($scope) {
$scope.title = '';
$scope.save = function() {
console.log($scope.title) -> undefined.....
}
})
答案 1 :(得分:0)
可能是一个范围问题,您的按钮不属于“测试”控制器。 试试这个:
<div ng-controller="TestCtrl">
<input type="input" ng-model="title"/>
<button type="button" ng-click="save()">Save</button>
</div>
查看正在运行的演示here
没有必要初始化“标题”,ng-model为你做。除非您没有在输入中键入值,否则ng-model将“title”初始化为undefined。
答案 2 :(得分:-1)
尝试注入$ scope,如下所示:
app.controller("test", ["$scope", function ($scope) {
$scope.save = function() {
console.log($scope.title);
};
}]);