簡體   English   中英

角度:指令和控制器之間的雙向綁定不起作用

[英]Angular: Two way binding between Directive and Controller does not work

我正在嘗試將Slider構建為Angular指令。 問題是,我需要控制器中Slider的值,因此可以通過Json將其發送到服務。 該值在指令中用於更新相應跨度的長度,並且每當移動滑塊時都應更新該值,該值應在指令和控制器中進行更新。 現在,它只將變量更新為我在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>

如果它是指令的控制器,則應這樣聲明它。 並也使用bindToController

angular.module('MyApp')
  .directive('slider', function ($rootScope) {
  return {
    controller: SliderController,
    controllerAs: 'vm',
    bindToController: {
      value: '='
    },
    replace: true,
    restrict: 'E',
    scope: true,
    ....

看看是否可行。

另外,不要忘記導入SliderController。

import SliderController from './slider.controller.js';

(或您的路徑/名稱是什么)

或者,如果導入不可用,則將控制器直接寫入與指令相同的文件中。 因此與上述相同,沒有導入,但添加了控制器:

function SliderController($scope) {
 ... etc
}

然后是控制器:SliderController; 指令中的一行應該起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM