如何使一个指令在angularjs中等待来自另一个指令的数据(甚至$log)?
在angularjs中,我已经看到了很多将一个指令数据传递给另一个指令的答案,但对我来说什么都不起作用 我有一个directivereadDirectoryContents,可以通过拖放文件夹来读取目录内容。现在,我想使用另一个directivebuildTree以树结构显示此目录内容 首先,我创建了一个指令如何使一个指令在angularjs中等待来自另一个指令的数据(甚至$log)?,angularjs,Angularjs,在angularjs中,我已经看到了很多将一个指令数据传递给另一个指令的答案,但对我来说什么都不起作用 我有一个directivereadDirectoryContents,可以通过拖放文件夹来读取目录内容。现在,我想使用另一个directivebuildTree以树结构显示此目录内容 首先,我创建了一个指令 <readDirectoryContents> <buildTree> 然后从这个指令中得到$scope.files,现在我创建了另一个指令 <rea
<readDirectoryContents>
<buildTree>
然后从这个指令中得到$scope.files,现在我创建了另一个指令
<readDirectoryContents>
<buildTree>
我想在其中使用$scope.files,所以这里的问题是两者都有
<readDirectoryContents> and <buildTree>
正在同时加载使$scope.files位于[]中
<buildTree> directive.
如何制作
<buildTree> to wait executing until we get $scope.files from <readDirectoryContents>. I am using console.log($scope.files); in my
<buildTree> directive to display the "files" but it is always showing [] as <readDirectoryContents> and <buildTree> are getting executed at the same time.
请记住,我不是问如何在UI中显示$scope.files,而是问如何执行
<buildTree> wait until the <readDirectoryContents> directive execution is done.(just to get $scope.files from first directive to next).
这类似于做出一个承诺,直到我们从另一个承诺中得到结果,但这里我是在指令的背景下提出的。如何使一个指令执行等待,直到我们从另一个指令获取数据
提前谢谢。我在代码中使用angularjs 1。我的问题是如何使console.log$scope.files在中不显示[]
<buildTree> directive.
也许您可以在buildTree指令中实现一个“watch” 尝试在buildTree指令中执行此操作:
//You need to receive files in your scope, I am considering that your
//files is shared between your directives.
$scope.$watch('files', function (newValue, oldValue) {
//The watch will execute everytime your files variable changes
if(newValue === oldValue) {
return;
}
//here you can set files to an internal variable of you directive
// or call a function to build your tree again
$scope.intFiles = newValue;
});
然后可以使用$scope.intFiles构建树。每次文件变量在readDirectoryContents中更新时,它都应该以逻辑方式反映到buildTree指令中
请注意,这是可能的解决方案之一,应该可以解决您的问题
请注意代码中的大量监视,以避免性能问题
有关更多信息,您可以查看有关手表的完整文档:您是否考虑过使用已经存在的文件目录插件,例如?不,我已经使用过。也许您应该更新您的问题,并让所有人知道您在这里实际做什么。该指令使用什么类型的范围?无、继承或隔离作用域?指令有控制器吗?或者它只是使用postLink功能?如果您展示代码,这会很有帮助。通常使用表达式和绑定来传递指令中的事件。使用单向