我正在嘗試構建一個Slider作爲Angular指令。問題是,我需要我的控制器中的滑塊的值,所以我可以通過Json將它發送到一個服務。該值在指令中用於更新相應跨度的長度,並且每當移動滑塊時應該更新值,該值應在指令和控制器中更新。現在它只是將變量更新爲我在Controller中設置的值,然後它保持原樣。Angular:Directive和Controller之間的雙向綁定不起作用
控制器:
angular.module('MyApp')
.controller('SliderController', ['$scope', '$http', function($scope, $http) {
$scope.m = 5;
$scope.m2 = 45;
}]);
指令:
angular.module('MyApp')
.directive('slider', function ($rootScope) {
return {
replace: true,
restrict: 'E',
scope:{
value: '='
},
link: function (scope, element, attrs) {
scope.header = attrs.header;
scope.unit = attrs.unit;
scope.min = attrs.min;
scope.max = attrs.max;
scope.step = attrs.step;
// scope.value = attrs.value;
// scope.model = attrs.ngModel;
var calculation = function() {
// console.log(scope.value);
return scope.value/scope.max * 100;
};
scope.onChange = function() {
if(isNaN(scope.value) || parseInt(scope.value) > parseInt(scope.max)) {
scope.value = scope.max;
}
scope.width = calculation();
};
},
templateUrl: '../html/slider.html'
};
});
HTML模板
<div class="slider">
<h3>{{header}}</h3>
<div class="progress">
<div class="span-back">
<span style="width:{{width}}%"></span>
</div>
<input class="input-range" type="range" min="{{min}}" max="{{max}}" step="{{step}}" data-ng-model="model" data-ng-change="onChange()" >
</div>
<div class="input-group">
<input type="text" class="input-value" ng-model="model" data-ng-change="onChange()">
<div class="input-base">{{unit}}</div>
</div>
指數HTML
<div ng-controller="SliderController">
<slider id="floating-div" header="My Slider" min="1" max="250" step="1" unit="testunit" data-ng-model="m2" value="m2"></slider>
</div>
我想你需要$觀察變化,imo。 – YOU
謝謝,但它似乎沒有工作。我只是獲取變量的名稱(「m2」),而不是在我的指令中傳遞的變量的值。 – Brainworm