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

How can i use controller object values in angular directive?

本文关键字:控制器 对象 指令 angular      更新时间:2023-09-26

一旦用户选择值,我希望这些对象值在指令中,例如$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: {
    message: "=",
    objToBind: "=" // add this one
},

在HTML中:

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

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

$scope.FileSizeString = $scope.objToBind.value

编辑

我猜你想动态地改变$scope.FileSizeString当你的选择改变,对吗?那么我认为你需要在指令中加入$watch,否则它永远是初始值,你不会意识到以后的变化。

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

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

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>

通过隔离作用域传递所需对象

HTML

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

JS

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

因为你已经在指令中创建了一个隔离作用域,所以通常不建议使用$parent属性,而是用来识别你想从你的父作用域中使用哪些变量。我建议你在html中传递你想要包含在指令中的变量,就像这样:

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

然后,在scope属性的指令中,你可以添加这些变量。

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

您可以使用:-

scope.$parent.propertyName

访问$scope级别的变量