javascript - 使用 transclude 属性时,对象和字符串的工作方式不同

标签 javascript angularjs angularjs-directive angularjs-scope

我读过一些关于在使用指令的 transinclude 属性时如何使用不同范围的文章。在调试我的代码时,我创建了以下代码片段。奇怪的是 _object_string 变量的行为不同。 _object 正在父范围内更新,而 _string 则没有。这是一个演示 http://jsbin.com/ruvixilukaci/1/edit

HTML:

<body ng-controller="MainCtrl">
  <div>Object: {{ _object }}</div>
  <div>String: {{ _string }}</div>

  <directive-example>
    <p><input type="text" ng-model="_object._string"></p>
    <p><input type="text" ng-model="_string" /></p>
  </directive-example>
</body>

Controller /指令源代码:

angular.module('app', [])

.controller('MainCtrl', function($scope) {
  $scope._object = {
    _string: 'Object string'
  };
  $scope._string = 'Default string';
})

.directive('directiveExample', function() {
  return {
    restrict: 'EA',
    transclude:true,
    template: '<div ng-transclude></div>'
  };
});

你知道发生了什么事吗?我也尝试过各种版本的 Angular.JS。任何帮助将不胜感激。

最佳答案

请阅读此处:Understanding scopes

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. What happens is that the child scope gets its own property that hides/shadows the parent property of the same name.

基本上,您的子作用域正在获取自己的 _string 属性副本,并且隐藏了父作用域的属性。

关于javascript - 使用 transclude 属性时,对象和字符串的工作方式不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25911322/

相关文章:

angularjs - Angular2 如何在 Guard 中获取目标 URL?

javascript - 两个日期相减会导致小时数不正确

javascript - 如何在 drop 函数中跟踪可拖动 div id 的 id

javascript - 删除和退格键在 radeditor 中不起作用

javascript - 我怎样才能摆脱 jquery 切换中的那些动画?

javascript - Angularjs - 进行同步调用

javascript - 在我的情况下,如何在两个 Controller 之间进行通信?

javascript - 正则表达式替换指令中的 html 标签

javascript - 我应该如何实现 Angular 选择指令?

angularjs - "clickable"和 "draggable"区域