我读过一些关于在使用指令的 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/