加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 我的ng模型真的需要有一个点,以避免子$范围问题?

发布时间:2020-12-17 08:27:41 所属栏目:安全 来源:网络整理
导读:根据 https://github.com/angular/angular.js/wiki/Understanding-Scopes,尝试数据绑定到附加到$ scope的原语是一个问题: Scope inheritance is normally straightforward,and you often don’t even need to know it is happening… until you try 2-way
根据 https://github.com/angular/angular.js/wiki/Understanding-Scopes,尝试数据绑定到附加到$ 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>

所以我遵循最佳实践?你能给我什么具体的例子,后者将救我从一些可怕的后果,将存在于前者?

很多东西都引入了新的范围。让我们说,在你的控制器中,你实际上想要添加标签:第一个标签是实际呈现,第二个标签是形式(所以你有一个实时预览)。

你决定使用一个指令:

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

那么,知道什么? < tabs>有自己的范围,打破你的控制器一个!所以当你编辑时,angular会做这样的事情在js:

$scope.theText = element.val();

这将不会遍历原型链尝试和设置父文本。

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

所以:这可能不需要现在,因为你还没有孩子范围在那个视图,但你不知道你是否要添加子模板,这可能最终修改文本本身,导致问题。为了未来证明你的设计,总是遵循规则,你不会有什么惊喜;)。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读