angularjs - 我的 ng-model 真的需要一个点来避免子 $scope 问题吗?

标签 angularjs angularjs-scope

根据https://github.com/angular/angular.js/wiki/Understanding-Scopes ,尝试将数据绑定(bind)到附加到您的 $scope 的原语是一个问题:

Scope inheritance is normally straightforward, and you often don't even need to know it is happening... until you try 2-way data binding (i.e., form elements, ng-model) to a primitive (e.g., number, string, boolean) defined on the parent scope from inside the child scope. It doesn't work the way most people expect it should work.



建议是

This issue with primitives can be easily avoided by following the "best practice" of always have a '.' in your ng-models



现在,我有一个非常简单的设置,它违反了这些规则:

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>

以便我遵循最佳做法?你能给我什么具体的例子,后者将使我免于前者会出现的可怕后果?

最佳答案

很多东西都引入了新的作用域。假设在您的 Controller 中,您实际上想要添加选项卡:第一个选项卡是实际渲染,第二个选项卡是表单(以便您进行实时预览)。

您决定为此使用指令:

<tabs>
  <tab name="view">
    <pre>{{theText|formatInSomeWay}}</pre>
  </tab>
  <tab name="edit" focus="true">
    <input type="text" ng-model="theText" />
  </tab>
</tabs>

嗯,知道吗? <tabs>有自己的范围,并打破了你的 Controller !所以当你编辑时,angular 会在 js 中做这样的事情:
$scope.theText = element.val();

它不会遍历原型(prototype)链来尝试设置 theText在 parent 身上。

编辑:为了清楚起见,我只使用“标签”作为示例。当我说“很多东西引入了一个新的范围”时,我的意思是:ng-include、ng-view、ng-switch、ng-controller(当然)等。

所以:目前可能不需要这,因为您在该 View 中还没有子范围,但您不知道是否要添加子模板,这最终可能会修改 theText自己,导致问题。为了将来证明您的设计,请始终遵循规则,然后您就不会感到惊讶了;)。

关于angularjs - 我的 ng-model 真的需要一个点来避免子 $scope 问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17178943/

相关文章:

java - gson.toJson() 在 Servlet 中抛出 StackOverflowError

angularjs - 在 angularjs Controller 内调用两次函数

javascript - Angular 工厂 promise 中的可变范围

javascript - 如何从 ng-repeat 中删除这个 li 元素?

javascript - Ng-Repeat on Same Collection,通过应用程序多次使用

AngularJS - 范围未更新

angularjs - 在 AngularJS 的服务中存储常量?

javascript - Angularjs &lt;style&gt; 标签

AngularJs 广播重复执行太多次

javascript - 不同的 ng-switch 动画