我如何在 angular 指令中使用控制器对象值?

How can i use controller object values in angular directive?

我在主页上有 angular select 一旦用户 select 值我想在指令中使用这些对象值,例如 $scope.selectedFileSize.value$scope.selectedFileSize.size 这样我就可以进一步在指令中实现逻辑。有什么想法吗?

main.html

<div class="col-md-3">
    <select class="form-control" ng-model="selectedFileSize" ng-options="item as item.value for item in FileSizeOptions" ng-change="onSizeChange()"><option value="">Select</option></select>
</div>

<progress-bar-custom message="event"></progress-bar-custom>

Controller.js

  $scope.onSizeChange = function(){
        $scope.maxMb = $scope.selectedFileSize.size;
        $scope.maxBytes = 3000;
        $scope.max = $scope.maxBytes;
        $scope.FileSizeString = $scope.selectedFileSize.value;
        console.log('FileSize',$scope.maxMb);
    }

directive.js

angular.module("App").directive('progressBarCustom', function() {
            return {
                restrict: 'E',
                scope: {
                    message: "="
                },
                templateUrl: '/view/partials/progressbar.html',
                controller: function($scope) {
                    var data = $scope.message;
                    var currentFileBytes = [];
                    var currentBytesSum;
                    $scope.maxBytes = 3000; // how to get these values from controller 
                    $scope.max = $scope.maxBytes;
                    $scope.FileSizeString = $scope.selectedFileSize.value; //How can i get these values from controller.

                    $scope.random = function(value) {
                        $scope.dynamic = value;
                        $scope.downloadPercentage = parseFloat((value / $scope.maxBytes) * 100).toFixed(0);
                        console.log('current value-dynamic', $scope.dynamic);
                    };

                }
            });

您可以使用:-

scope.$parent.propertyName

在您的控制器中访问 $scope 级变量

通过隔离范围传递您需要的对象

HTML

<progress-bar-custom message="event" file="selectedFileSize"></progress-bar-custom>

JS

        restrict: 'E',
        scope: {
            message: "=",
            file: "="
        },
        templateUrl: '/view/partials/progressbar.html',

您可以将它们定义为指令范围内的绑定:

scope: {
    message: "=",
    objToBind: "=" // add this one
},

并且在 HTML 中:

<progress-bar-custom message="event" obj-to-bind="selectedFileSize"></progress-bar-custom>

然后你可以在你的指令控制器中访问它:

$scope.FileSizeString = $scope.objToBind.value

编辑

我猜您想在 select 更改时动态更改 $scope.FileSizeString,对吗?那我觉得你需要在directive中$watch,不然一直是初始值,以后的变化你都不知道

我不知道你是如何实现你的应用程序的,所以我写了一个简单的演示来演示关键点:

  1. 我将您的默认 select 选项移动到 ng-options 数组中,而是使用 ng-init 设置默认选项。
  2. 我在指令中使用 $watch 来观察绑定值的变化。

var app = angular.module('myApp', [])

app.controller('myCtrl', ['$scope', function($scope) {
  $scope.fileSizes = [
    {size: -1, value: 'Select'},
    {size: 1, value: '1MB'},
    {size: 2, value: '2MB'},
    {size: 3, value: '3MB'}
  ]

  $scope.onSizeChange = function() {
    console.log($scope.selected.size)
  }
}])

app.directive('myDirective', function() {
  return {
    restrict: 'E',
    scope: {
      selectedSize: '='
    },
    template: '<div style="font-family:monospace"><p><b>Your choice:</b> {{myChoice}}</p><p><b>Actual Choice:</b> {{selectedSize}}</p></div>',
    controller: function($scope) {
      $scope.myChoice = ''
      $scope.$watch('selectedSize', function (newVal, oldVal) {
        $scope.myChoice = (newVal && newVal.size !== -1) ? newVal.value : ''
      })
    }
  }
})
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="myCtrl">
    <select ng-options="opt as opt.value for opt in fileSizes"
            ng-model="selected"
            ng-init="selected = fileSizes[0]"
            ng-change="onSizeChange()">
    </select>
    <my-directive selected-size="selected"></my-directive>
  </div>
</div>

由于您在指令中创建了隔离范围,因此通常不建议使用 $parent 属性,而是要从父范围中确定要使用的变量。我建议您在 html 中传入要包含在指令中的变量,如下所示:

<progress-bar-custom message="event" fileSize="selectedFileSize.size" fileValue="selectedFileSize.value"></progress-bar-custom>

然后,在您的范围属性中的指令中,您可以添加变量。

scope: {
     message: "=",
     fileSize: "=",
     fileValue: "="
 },