一旦用户选择了值,我在主页面上进行了角度选择我想在指令中使用这些对象值,例如NOTIFICATION
和$scope.selectedFileSize.value
,这样我就可以在指令中进一步实现逻辑。有什么想法吗?
main.html中
$scope.selectedFileSize.size
Controller.js
<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>
directive.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);
}
答案 0 :(得分:2)
您可以在指令范围内将它们定义为绑定:
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
指令,否则它总是初始值,你不会意识到未来的变化。
我并不确切知道您如何实施您的应用,所以我写了一个简单的演示来演示关键点:
ng-options
数组,而是使用ng-init
设置默认选项。$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 : ''
})
}
}
})
&#13;
<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>
&#13;
答案 1 :(得分:1)
将您所需的对象传递到隔离范围
HTML
<progress-bar-custom message="event" file="selectedFileSize"></progress-bar-custom>
JS
restrict: 'E',
scope: {
message: "=",
file: "="
},
templateUrl: '/view/partials/progressbar.html',
答案 2 :(得分:1)
由于您已在指令中创建了隔离范围,因此通常不建议使用$ parent属性,而是要确定要从父范围使用哪些变量。我建议您在html中传入要包含在指令中的变量,如下所示:
<progress-bar-custom message="event" fileSize="selectedFileSize.size" fileValue="selectedFileSize.value"></progress-bar-custom>
然后,在scope属性的指令中,您可以添加变量。
scope: {
message: "=",
fileSize: "=",
fileValue: "="
},
答案 3 :(得分:0)
您可以使用: -
scope.$parent.propertyName
在控制器内部访问$ scope level变量