【发布时间】:2013-06-15 06:16:57
【问题描述】:
根据https://github.com/angular/angular.js/wiki/Understanding-Scopes,尝试将数据绑定到附加到$scope 的原语是一个问题:
范围继承通常很简单,而且您通常甚至不需要知道它正在发生...直到您尝试将 2 路数据绑定(即,表单元素,ng-model)到基元(例如,数字, string, boolean) 从子作用域内定义在父作用域上。它并没有像大多数人期望的那样工作。
建议是
遵循始终使用 '.' 的“最佳实践”,可以轻松避免原语的这个问题。在你的 ng 模型中
现在,我有一个违反这些规则的非常简单的设置:
HTML:
<input type="text" ng-model="theText" />
<button ng-disabled="shouldDisable()">Button</button>
JS:
function MyController($scope) {
$scope.theText = "";
$scope.shouldDisable = function () {
return $scope.theText.length >= 2;
};
}
这真的很糟糕吗?当我开始尝试使用子范围时,这会以某种可怕的方式把我搞砸吗?
我需要把它改成类似的东西吗
function MyController($scope) {
$scope.theText = { value: "" };
$scope.shouldDisable = function () {
return $scope.theText.value.length >= 2;
};
}
和
<input type="text" ng-model="theText.value" />
<button ng-disabled="shouldDisable()">Button</button>
以便我遵循最佳实践?你能给我什么具体的例子,后者可以让我免于前者会出现的可怕后果?
【问题讨论】: