我需要一些帮助来了解如何在firstCtr控制器中访问$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)
}
我可以用rootcope做到这一点,但这似乎是一个坏主意。有没有更好的方法来恢复此范围?
答案 0 :(得分:1)
有几种方法可以做到这一点。
一种方法是在imageUpload指令中,在父作用域中注入一个属性,以便该父作用域的控制器可以访问它并执行它与它有关的操作。所以在你的imageUpload指令控制器函数中:
$scope.$parent.imageUpload = {};
$scope.$parent.image_File = $files[0];
对于更强大的解决方案,我可能会在imageUpload指令中使用require
关键字,因此它可以可靠地访问firstCtr控制器并在其中设置属性。
.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];
};
}
}
});