2017-08-08 64 views
0

我见过这么多的答案,将一个指令数据传递给angularjs中的另一个指令,但没有任何工作适合我。

我有一个指令(readDirectoryContents)通过拖放文件夹来读取目录内容。现在我想使用另一个指令(buildTree)在树结构中显示这个目录内容。

首先,我创建了一个指令

<readDirectoryContents> 

,然后得到$ scope.files从这个指令,现在我创造了另一个指令

<buildTree> 

中,我想用$ scope.files,所以这里的问题是这两个都是

<readDirectoryContents> and <buildTree> 

正在加载,同时使$ scope.files是[] i ñ

<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. 

请记住,我不是问如何显示$ 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. 
+0

你有没有考虑过使用已经存在的文件目录的插件,如[这一个](https://github.com/angular- ui-tree/angular-ui-tree)? –

+0

不,我已经使用https://www.html5rocks.com/en/tutorials/file/filesystem/ –

+0

也许你应该更新你的问题,让每个人都知道你在这里实际做了什么。 –

回答

1

显示[]也许你可以实现你的buildTree指令中的“手表”。

尽量做到这一点,你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指令(逻辑地指向您的手表)。

请注意,这是可能的解决方案之一,并应解决您的问题。

请注意代码中的很多手表,以避免性能问题。

欲了解更多信息,你可以看到手表的完整文档:$rootScope.Scope

相关问题