javascript - 如何从另一个 Controller 中的指令访问范围

标签 javascript angularjs

我需要一些帮助来了解如何在我的 firstCtr Controller 中访问 $scope.imageUpload.image_file

我有以下标记:

HTML:

<div ng-controller="firstCtr">
 <div image-upload></div>
</div>

imageload 指令创建一个名为 $scope.imageUpload.image_file 的新范围,它工作正常。

   .directive('imageUpload', function () {
    // Directive used to display a badge.
    return {
        restrict: 'A',

        replace: true,
        templateUrl: "/static/html/partials/directives/imageToolsUpload.html",
        controller: function ($scope) {
           $scope.onImageSelect = function ($files) {
               console.log( $scope.project);
                $scope.imageUpload = {};
                $scope.imageUpload.image_file =  $files[0];
        };
        }
    }
});

但是,当我随后尝试在 firstCtr 中获取范围 $scope.imageUpload.image_file 时,它​​是未定义的。

 .controller("firstCtr", ['$scope', '$rootScope', "$location", etc.....

           $scope.actionClick = function () {
                 console.log($scope.imageUpload)
            }

我可以使用 rootscope 来做到这一点,但这似乎是个坏主意。有没有更好的方法来备份这个范围?

最佳答案

有几种方法可以做到这一点。

一种方法是在您的 imageUpload 指令中,在父作用域中注入(inject)一个属性,这样父作用域的 Controller 就可以访问它并执行它必须做的事情。所以在你的 imageUpload 指令 Controller 函数中:

$scope.$parent.imageUpload = {};
$scope.$parent.image_File = $files[0];

对于更强大的解决方案,我可能会在您的 imageUpload 指令中使用 require 关键字,因此它可以可靠地访问 firstCtr Controller 并在其中设置属性。

.directive('imageUpload', function () {
    // Directive used to display a badge.
    return {
        restrict: 'A',
        require: 'firstCtr'
        replace: true,
        templateUrl: "/static/html/partials/directives/imageToolsUpload.html",
        controller: function ($scope, element, attrs, firstCtr) {
           $scope.onImageSelect = function ($files) {
               console.log( $scope.project);
               firstCtr.imageUpload = {};
               firstCtr.imageUpload.image_file =  $files[0];
        };
        }
    }
});

关于javascript - 如何从另一个 Controller 中的指令访问范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25387555/

相关文章:

javascript - 使用 Jasmine 测试 Angular.js Controller 而不模拟工厂

angularjs - 如何获取 MEAN 堆栈中的服务器时间? (MongoDB、Express、Angular、 Node )

javascript - AngularJS 如何正确使用 ng-model 作为类?

javascript - View 中 Controller 的 Angular 重用函数值

javascript - AngularJS 中的多个 $http 调用

javascript - 带有数组的 Angular ng 模型

javascript - Express with node.js 不压缩 jpeg 图片

javascript - 单击 <the> 将类添加到 div

javascript - 单击 jQuery -> 使用 PHP 将元素写入数据库

javascript - Titanium SDK 的奇怪行为 - 选项卡必须只有一个子选项