我需要一些帮助来了解如何在我的 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/