Update $ scope with data from a directive

0

I have the following directive that I have taken from google (to create a chronometer):

    .directive('cronometro', function () {
    var stopWatch = function(elem, options, attrs) {

      var hora = 0;
      if (attrs.start == 0) {
        //alert('Sin inicialziar');
        var tiempo_inicial = 0;

      } else {

        hora = attrs.start.split(":");


      }

        var timer       = createTimer(),
            startButton = createButton("►", start),
            //stopButton  = createButton("∎", stop),
            resetButton = createButton("&#8635", reset),
            offset,
            clock,
            interval;

        // default options
        options = options || {};
        options.delay = options.delay || 150;

        // append elements
        elem.appendChild(timer);
        elem.appendChild(startButton);
        //elem.appendChild(stopButton);
        elem.appendChild(resetButton);

        // initialize
        reset(false);

        // private functions

        function createTimer() {
          var div = document.createElement("div"); 
          div.id = "contenedor_crono";

          return div;
        }

        function createButton(action, handler) {
            var button = document.createElement("button");
            button.innerHTML = action;
            button.className = "boton_crono";
            button.addEventListener("click", function(event) {
                handler();
                event.preventDefault();
            });
            return button;
        }

        function start() {
            if (!interval) {
                offset   = Date.now();
                interval = setInterval(update, options.delay);
            } else {
                clearInterval(interval);
                interval = null;                  
            }
        }


        function reset(reseteo) {
            if (reseteo !== false) {
              hora = '00:00:00:000'.split(":");
            }
            clock = 0;
            render();
        }

        function update() {
            clock += delta();
            render();
        }

        function getClockInfo() {
            var hours = Math.floor( ((clock/1000) / 60) / 60 ),
                minutes = Math.floor( ((clock/1000) / 60) -  hours * 60 ),
                seconds = 
                    Math.floor( 
                        (clock/1000) -  
                        (minutes * 60) - 
                        (hours * 60 * 60)
                    ),
                milliSeconds =
                    Math.floor(
                        clock -
                        (seconds * 1000) -
                        (minutes * 60 * 1000) -
                        (hours * 60 * 60 * 1000)
                    );


            return {
                'hours' : hours,
                'minutes' : minutes,
                'seconds' : seconds,
                'milliSeconds' : milliSeconds,
            };
        }

        function render() {
            var clockInfo = getClockInfo();

              var horaCrono = parseInt(hora[0]) + parseInt(clockInfo.hours.toString());

              var minutoCrono = parseInt(hora[1]) + parseInt(clockInfo.minutes.toString());


              var segundoCrono = parseInt(hora[2]) +  parseInt(clockInfo.seconds.toString());

              var milesimasCrono = parseInt(hora[3]) +  parseInt(clockInfo.milliSeconds.toString());

              if (milesimasCrono > 999) { milesimasCrono = 999;} //temporal fix
              //console.log(milesimasCrono) ;


           /**/ timer.innerHTML =

              '<div class="reloj_crono" id="Horas">' + horaCrono.toString().zeroPad(2) + ':</div>' +
              '<div class="reloj_crono" id="Minutos">' + minutoCrono.toString().zeroPad(2) + ':</div>' +
              '<div class="reloj_crono" id="Segundos">'+ segundoCrono.toString().zeroPad(2) + ':</div> ' +
              '<div class="reloj_crono" id="Centesimas">'+ milesimasCrono.toString().zeroPad(2)+'</div>' 

              ;/**/
        }

        function delta() {
            var now = Date.now(),
                d   = now - offset;

            offset = now;

            return d;
        }

        // public API
        this.start  = start;
        this.reset  = reset;
    };

    return {
        restrict: 'E',
        //transclude: true,
        replace: true,
        scope: { },


        link: function (scope, element, attrs) {

            var sw = new stopWatch(element[0],element,attrs);


        }
    };
})

In the html I have the following:

<cronometro start="{{inicio_crono}}" value="valor_crono"></cronometro>

I give the buttons and it works correctly, but I am not able to put $ scope.valor_crono the value of the chronometer.

In the link (of the directive) I tried with obj.value and with attrs.value , without success

How do I update the scope with the value that the directive has?

    
asked by j0se 20.09.2017 в 19:17
source

1 answer

0

With scope.$eval() you can achieve it. You only have to specify the name of the model in the attribute start and in the directive obtain the value with $eval() .

Here is a simple example of how to access the value of a model by specifying in a custom attribute:

angular.module("app",[])
.controller("ctrl",function($scope){
  $scope.modelo = {};
  $scope.modelo.inicio = "12:33";
})
.directive("cronometro",function(){
  return{
   restrict:"E",
   link:function($scope,$element,$attrs) {
   
      var valorModelo = $scope.$eval($attrs.start);
      alert("el valor del modelo asignado es " + valorModelo);
   }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <cronometro start="modelo.inicio" />
</div>

So in your case it would be like that. I do not know why it should not work, you'll have to fix the logic. At least you already know how to read the value of a model from an address:

  angular.module("app",[]).controller("ctrl", function($scope){
  
  $scope.model = {
    start: "01:15"
  };
  
  }).directive('cronometro', function () {
  
    var stopWatch = function(elem, options, attrs, start) {

      var hora = 0;
      if (start == 0) {
        //alert('Sin inicialziar');
        var tiempo_inicial = 0;
      } else {
        hora = attrs.start.split(":");
      }

        var timer       = createTimer(),
            startButton = createButton("&#9658;", start),
            //stopButton  = createButton("&#8718;", stop),
            resetButton = createButton("&#8635", reset),
            offset,
            clock,
            interval;

        // default options
        options = options || {};
        options.delay = options.delay || 150;

        // append elements
        elem.appendChild(timer);
        elem.appendChild(startButton);
        //elem.appendChild(stopButton);
        elem.appendChild(resetButton);

        // initialize
        reset(false);

        // private functions

        function createTimer() {
          var div = document.createElement("div"); 
          div.id = "contenedor_crono";

          return div;
        }

        function createButton(action, handler) {
            var button = document.createElement("button");
            button.innerHTML = action;
            button.className = "boton_crono";
            button.addEventListener("click", function(event) {
                handler();
                event.preventDefault();
            });
            return button;
        }

        function start() {
            if (!interval) {
                offset   = Date.now();
                interval = setInterval(update, options.delay);
            } else {
                clearInterval(interval);
                interval = null;                  
            }
        }


        function reset(reseteo) {
            if (reseteo !== false) {
              hora = '00:00:00:000'.split(":");
            }
            clock = 0;
            render();
        }

        function update() {
            clock += delta();
            render();
        }

        function getClockInfo() {
            var hours = Math.floor( ((clock/1000) / 60) / 60 ),
                minutes = Math.floor( ((clock/1000) / 60) -  hours * 60 ),
                seconds = 
                    Math.floor( 
                        (clock/1000) -  
                        (minutes * 60) - 
                        (hours * 60 * 60)
                    ),
                milliSeconds =
                    Math.floor(
                        clock -
                        (seconds * 1000) -
                        (minutes * 60 * 1000) -
                        (hours * 60 * 60 * 1000)
                    );


            return {
                'hours' : hours,
                'minutes' : minutes,
                'seconds' : seconds,
                'milliSeconds' : milliSeconds,
            };
        }

        function render() {
            var clockInfo = getClockInfo();

              var horaCrono = parseInt(hora[0]) + parseInt(clockInfo.hours.toString());

              var minutoCrono = parseInt(hora[1]) + parseInt(clockInfo.minutes.toString());


              var segundoCrono = parseInt(hora[2]) +  parseInt(clockInfo.seconds.toString());

              var milesimasCrono = parseInt(hora[3]) +  parseInt(clockInfo.milliSeconds.toString());

              if (milesimasCrono > 999) { milesimasCrono = 999;} //temporal fix
              //console.log(milesimasCrono) ;


           /**/ timer.innerHTML =

              '<div class="reloj_crono" id="Horas">' + horaCrono.toString().zeroPad(2) + ':</div>' +
              '<div class="reloj_crono" id="Minutos">' + minutoCrono.toString().zeroPad(2) + ':</div>' +
              '<div class="reloj_crono" id="Segundos">'+ segundoCrono.toString().zeroPad(2) + ':</div> ' +
              '<div class="reloj_crono" id="Centesimas">'+ milesimasCrono.toString().zeroPad(2)+'</div>' 

              ;/**/
        }

        function delta() {
            var now = Date.now(),
                d   = now - offset;

            offset = now;

            return d;
        }

        // public API
        this.start  = start;
        this.reset  = reset;
    };

    return {
        restrict: 'E',
        //transclude: true,
        replace: true,
        link: function (scope, element, attrs) {

            var start = scope.$eval(attrs.start);
            console.log("valor inicial:" , start);
            alert("el valor ingresado es: " + start);
            var sw = new stopWatch(element[0],element,attrs, start);


        }
    };
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<cronometro start="model.start" />
</div>
    
answered by 20.09.2017 в 22:51