这是显示问题的小提琴.http://jsfiddle.net/Erk4V/1/
如果我在ng-if中有ng模型,则该模型似乎不能按预期工作.
我想知道这是一个错误还是我误解了正确的用法.
<div ng-app >
<div ng-controller="main">
Test A: {{testa}}<br />
Test B: {{testb}}<br />
Test C: {{testc}}<br />
<div>
testa (without ng-if): <input type="checkbox" ng-model="testa" />
</div>
<div ng-if="!testa">
testb (with ng-if): <input type="checkbox" ng-model="testb" />
</div>
<div ng-if="!someothervar">
testc (with ng-if): <input type="checkbox" ng-model="testc" />
</div>
</div>
</div>
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)
所以我遵循最佳做法?你可以给我什么样的具体例子,后者将使我免于前者出现的一些可怕后果?