Javascript 如何在隔离范围指令内访问此范围变量?
这是我在psuedo代码中的情况Javascript 如何在隔离范围指令内访问此范围变量?,javascript,angularjs,Javascript,Angularjs,这是我在psuedo代码中的情况 <div data-ng-controller="test"> <div isolated-directive> <select ng-model="testControllerScopeVar">...</select> </div> <div ng-if="some condition that uses testControllerScopeVar
<div data-ng-controller="test">
<div isolated-directive>
<select ng-model="testControllerScopeVar">...</select>
</div>
<div ng-if="some condition that uses testControllerScopeVar"></div>
</div>
...
在我添加独立指令
之前,它工作得很好,现在它被添加(范围:true
)了ng if
不再工作,因为我认为它在指令内部被吃掉了
在不涉及html和
独立指令的结构的情况下,最有效的方法是什么?一种方法是将控制器变量映射到独立作用域,并将独立作用域变量附加到内部ng模型
因此,您的HTML将如下所示:
<div data-ng-controller="test">
<div isolated-directive="testControllerScopeVar">
<select ng-model="isolatedScopeVar">...</select>
</div>
<div ng-if="some condition that uses testControllerScopeVar"></div>
</div>
app.directive('isolatedDirective', function () {
return {
scope: {
isolatedScopeVar: '=isolatedDirective'
}
};
});
您可以尝试jQuery获取该值并将其分配给新的范围变量。像这样的
HTML
工作小提琴好吧,看来一旦我知道了解决办法,它就这么简单了
<div data-ng-controller="test as testCtrl">
<div isolated-directive>
<select ng-model="testCtrl.testControllerScopeVar">...</select>
</div>
<div ng-if="testCtrl.testControllerScopeVar == 'whatever'"></div>
</div>
...
ControllerAs允许我专门访问正确的范围并完美地工作,感谢您的时间和投入您是否对您的独立指令启用了transclusion(例如transclude:true
)并在隔离指令的模板中包含了一个
标记?您不认为在隔离范围内创建模型有点违反直觉吗,但是引用的模型超出了这个范围吗?@rob不,但我不想碰它directive@Yerken该指令是一个复杂的可停靠指令,但设计要求该下拉列表位于可停靠指令内部,以便其停靠。显示/隐藏的内容基于下拉列表。我还能做什么?唯一的方法是修改隔离指令。您可能需要启用转换,删除它的隔离作用域,或者将变量作为@Jack A传递出去。suggestedI根本不想修改该指令,因为它是一个非常复杂的指令,能够很好地完成自己的工作。没有别的办法吗?@Huangism在不了解更多有关指令的情况下,很难说你有什么选择。你试过你想做的事了吗?如果指令不排除,也不使用模板,那么它将按照您编写的方式工作。例如,看看这把小提琴:这个项目没有jquery,也不需要它,我找到了解决方案并将其作为答案发布
var app = angular.module('TestApp', []);
app.controller('test', function($scope) {
var element = angular.element(document.querySelector('#isolatedVar'));
element.bind('keyup', function() {
$scope.isolatedVar = element.val();
console.log($scope.isolatedVar);
$scope.$watch('isolatedVar', function() {});
});
});
app.directive('isolatedDirective', function() {
return {
scope: true
};
});
<div data-ng-controller="test as testCtrl">
<div isolated-directive>
<select ng-model="testCtrl.testControllerScopeVar">...</select>
</div>
<div ng-if="testCtrl.testControllerScopeVar == 'whatever'"></div>
</div>