可能是愚蠢的问题,但我的html表单有简单的输入和按钮:
<input type="text" ng-model="searchText" />
<button ng-click="check()">Check!</button>
{{ searchText }}
Run Code Online (Sandbox Code Playgroud)
然后在控制器中(从routeProvider调用模板和控制器):
$scope.check = function () {
console.log($scope.searchText);
}
Run Code Online (Sandbox Code Playgroud)
为什么我在单击按钮时看到视图更新正确但在控制台中未定义?
谢谢!
更新:似乎我已经解决了这个问题(之前不得不提出一些解决方法):只需要将我的属性名称更改searchText为search.text,然后$scope.search = {};在控制器中定义空对象并瞧...不知道为什么它正在工作虽然;]
我有以下输入并需要它们的值:
<input type="hidden" ng-model="movie" value="harry_potter"/>
<input type="text" ng-model="year" value="2000"/>
Run Code Online (Sandbox Code Playgroud)
我该怎么做才能获得每个输入的值?
根据https://github.com/angular/angular.js/wiki/Understanding-Scopes,尝试数据绑定到附加到您的原语的问题是一个问题$scope:
范围继承通常很简单,你通常甚至不需要知道它正在发生......直到你尝试双向数据绑定(即表单元素,ng-模型)到一个原语(例如,数字,字符串, boolean)在子范围内从父范围定义.它不像大多数人期望的那样工作.
建议是
通过遵循始终具有'.'的"最佳实践",可以轻松避免与原语的这个问题.在您的ng模型中
现在,我有这个非常简单的设置违反了这些规则:
HTML:
<input type="text" ng-model="theText" />
<button ng-disabled="shouldDisable()">Button</button>
Run Code Online (Sandbox Code Playgroud)
JS:
function MyController($scope) {
$scope.theText = "";
$scope.shouldDisable = function () {
return $scope.theText.length >= 2;
};
}
Run Code Online (Sandbox Code Playgroud)
这真的很糟糕吗?当我开始尝试使用子范围时,这是否会以某种可怕的方式使我搞砸了?
我是否需要将其更改为类似的内容
function MyController($scope) {
$scope.theText = { value: "" };
$scope.shouldDisable = function () {
return $scope.theText.value.length >= 2;
};
}
Run Code Online (Sandbox Code Playgroud)
和
<input type="text" ng-model="theText.value" />
<button ng-disabled="shouldDisable()">Button</button>
Run Code Online (Sandbox Code Playgroud)
所以我遵循最佳做法?你可以给我什么样的具体例子,后者将使我免于前者出现的一些可怕后果?