Javascript 嵌套指令未正确继承父范围
嵌套指令和从父级继承范围有问题。我想从中继承的范围恰好是一个独立的范围。我有下面的代码 test.htmlJavascript 嵌套指令未正确继承父范围,javascript,angularjs,inheritance,angularjs-directive,isolate-scope,Javascript,Angularjs,Inheritance,Angularjs Directive,Isolate Scope,嵌套指令和从父级继承范围有问题。我想从中继承的范围恰好是一个独立的范围。我有下面的代码 test.html <div ng-controller="testCtrl as test"> <special-select data-selected-item="test.selectedThing"> <special-select-selected-item></special-select-selected-item> </
<div ng-controller="testCtrl as test">
<special-select data-selected-item="test.selectedThing">
<special-select-selected-item></special-select-selected-item>
</special-select>
</div>
特殊输入.js
angular
.module('testApp', ['special-inputs'])
.controller('testCtrl', [
function() {
this.items = [
{ id: 1, name: 'alex 1', displayName:"alex 1 dn", imageUrl: 'http://placehold.it/505x100' }
];
this.selectedThing = this.items[0];
this.test = function() {
console.log('test fn');
}
}
]);
angular
.module('special-inputs', [])
.directive('specialSelect', [
function() {
return {
restrict: 'E',
replace: true,
transclude: true,
template: '<div class="container" ng-transclude></div>',
scope: {
selectedItem: '='
},
link: {
pre: function(scope) {
console.log('parent link pre - ', scope.selectedItem);
},
post: function(scope) {
console.log('parent link post - ', scope.selectedItem);
}
}
}
}
])
.directive('specialSelectSelectedItem', [
function() {
return {
restrict: 'E',
replace: true,
transclude: true,
template: '<div class="selected" ng-transclude></div>',
scope: true,
link: {
pre: function(scope) {
console.log('child link pre - ', scope.selectedItem);
},
post: function(scope) {
console.log('child link post - ', scope.selectedItem);
}
}
}
}
])
我已经尝试使用
作用域。$watch
和attrs.$observe
填充值如果子指令不需要隔离作用域,那么不给它一个?您可以在子指令上设置作用域:true
,它将从父作用域继承。如果希望作用域相同,则需要在child指令上设置scope:false
,它将具有与其父指令相同的确切作用域。前者似乎就是你想要的。干杯@Rorschach120,scope:true似乎就是这样。只是想知道,我上面的东西不应该有用吗?它正在创建一个隔离作用域,但从父级获取指定的项。它不起作用,因为该值实际上没有传递到子指令的作用域。使用$parent
可以工作,但这是一种非常糟糕的做法。您需要通过在scope
定义中设置的双向绑定将selectedItem
传递到孩子的隔离作用域<代码>好的,太好了。谢谢欣赏help@vernak2539-在html中,您有,这意味着您希望通过指令中的test.selectedThing to dataSelectedItem。但在指令中,您在scope属性中定义了selectedItem。应该是dataSelectedItem。
2015-12-29 15:13:44.258 special-select.js:35 parent link pre - Object {id: 1, name: "alex 1", displayName: "alex 1 dn", imageUrl: "http://placehold.it/505x100"}
2015-12-29 15:13:44.258 special-select.js:64 child link pre - undefined
2015-12-29 15:13:44.260 special-select.js:67 child link post - undefined
2015-12-29 15:13:44.260 special-select.js:38 parent link post - Object {id: 1, name: "alex 1", displayName: "alex 1 dn", imageUrl: "http://placehold.it/505x100"}