Angularjs - ng-init功能完成后的Call Directive

时间:2014-10-30 15:57:56

标签: javascript angularjs angularjs-directive angularjs-controller

我试图在我的html文件中调用ng-init中的函数。 该函数进行API调用并提供数据。我将该数据分配给范围变量,并将该范围变量传递给指令。

控制器首先击中。但是在APIi调用完成指令之前就已经命中了。所以我传递给控制器​​的范围变量是未定义的。

App.directive('foldertree', function () {
    return {
        restrict: 'A',
        scope: {
            'inputfromapicall': '=',
            'fileName': "="
        },
        link: function (scope, element, attrs, ngModelCtrl) {

            return $timeout(function() {               
                $('#divid').fileTree({
                    root: scope.inputfromapicall, //undefined
                    script: '/project/current/source/data/jqueryFileTree.jsp',
                    expandSpeed: 1,
                    collapseSpeed: 1,
                    multiFolder: false
                }, function (file) {
                    scope.fileName = file;                   
                    scope.$apply();
                });
            });
        }
    };
});

以上是我的指令代码

很抱歉发布了一个模糊的问题。希望有人帮我修复。

1 个答案:

答案 0 :(得分:2)

正如MajoB在评论范围中提到的那样。$ watch完成了这个伎俩。这是我更新的指令代码。

automateOnApp.directive('foldertree', ['$timeout', function($timeout){
    return {
        restrict: 'A',
        scope: {
            'inputfromapicall': '=',
            'fileName': "="
        },
        link: function (scope, element, attrs, ngModelCtrl, controller) {
            scope.fileName = '';
            return $timeout(function() {


                scope.$watch(function () {                           
                        return scope.inputfromapicall;
                }, function(newVal) {                      

                        if(!angular.isUndefined(scope.inputfromapicall)){
                            $('#divid').html('');
                            $('#divid').fileTree({
                                    root: newVal,
                                    script: '/project/current/source/data/jqueryFileTree.jsp',
                                    expandSpeed: 1,
                                    collapseSpeed: 1,
                                    multiFolder: false
                            }, function (file) {                        
                                    scope.fileName = file;                   
                                    scope.$apply();
                            });
                        }
                });

            });
        }
    };
}]);

希望它能帮助未来的人