Use driver without $ scope

1

angular.module('App')
    .config(function ($stateProvider) {
        $stateProvider
            .state('solicitud', {
                url: 'solicitud',
                controller: 'SolCtrl as sol',
                templateUrl: '/scripts/app/estados/solicitud/solicitud.html'
            })
    });


angular.module('App').controller('SolCtrl', solCtrl);

function solCtrl($http, $scope) {

    var solicitud = this;
    solicitud.name = 'Solicitud //ABANCA';

    function respuestaCtrl() {
        this.solicitud = function () {
            alert('funciona');

        }
    }


    $scope.datos = {};
    $scope.datos.cantidad = "";
    $scope.datos.cuota = "";
    $scope.datos.plazos = "";
    $scope.datos.tipo = "";

    $scope.formulario = {}
    $scope.formulario.cantidad = 0;
    $scope.formulario.plazos = 0;
    $scope.formulario.tipo = "hipotecario";

    var logresultado = function (respuesta) {
        $scope.datos.cantidad = $scope.cantidad;
        $scope.datos.cuota = $scope.cuota;
        $scope.datos.plazos = $scope.plazos
        $scope.datos.tipo = $scope.tipoCredito;
    };

    $scope.selected = 'Crédito hipotecario';
    $scope.radioOptions = [
       { name: 'Crédito hipotecario', value: 'hipotecario' },

       { name: 'Crédito personal', value: 'personal' },
    ];

    $scope.showMe = false;

    $scope.myForm = function () {

        var baseURL = 'http://localhost:58498/api/cuota?';
        var cantidad = 'cantidad=' + $scope.formulario.cantidad;
        var plazos = '&plazos=' + $scope.formulario.plazos;
        var tipo = '&tipo=' + $scope.formulario.tipo;

        $scope.get(baseURL + cantidad + plazos + tipo).success(function (respuesta) {

            console.log(respuesta)
            logresultado(respuesta);

            console.log('entra aqui')
            $scope.showMe = !$scope.showMe;

        })

    }


   

};
<div class="col-md-6">
    <form action="http://localhost:58498/api/Cuota" class="form-horizontal"
          method="get" role="form" id="formulario-cuotas">
        
        <div class="form-group">
            <label class="control-label" for="Cuotas">¿Cuánto quieres pedir?</label>
            <input class="form-control" data-val="true"
                   data-val-cuotas="El campo de las Cuotas está vacío. No es válido"
                   data-val-required="El campo Cuotas es obligatorio." id="Cuotas"
                   name="cantidad" type="number" value=""
                   ng-model="formulario.cantidad">
            <span class="field-validation-valid text--danger"
                  data-valmsg-for="Cuotas" data-valmsg-replace="true"></span>
        </div>

        <p>
            "Con el préstamo 24h puedes pedir a partir <br>
            de 500€, pero para cantidades de hasta 3000€ <br>
            tiene que ser en la "<a href="/es/tarjetas/tarjetas-credito/tarjeta-visa-clip" target="_blank">
                modalidad de
                tarjeta <br>
            </a>
            ".Por eso este simulador empieza en 3000€ que <br>
            es lo mínimo que puedes pedir en la modalidad <br>
            de préstamo. Ten en cuenta que no puedes <br>
            solicitar más de lo que cuesta lo que vayas <br>
            financiar."
        </p>


        <br>

        <div class="form-group">
            <label for="Plazo" class="control-label">¿Cuándo deseas devolverlo?</label>
            <input class="form-control" data-val="true"
                   data-val-cuotas="El campo de los plazos está vacío. No es válido"
                   data-val-required="El campo Plazos es obligatorio." id="Plazos"
                   name="plazos" type="text" value=""
                   ng-model="formulario.plazos">
            <span class="field-validation-valid text--danger"
                  data-valmsg-for="Plazos" data-valmsg-replace="true"></span>
        </div>

        <p>
            "Puedes devolverlo en un plazo maximo de 96 meses,<br>
            osea, 8 años"
        </p>



        <div class="form-check">
            <label class="form-check-label" ng-repeat="option in radioOptions">
                <input type="radio" ng-model="formulario.tipo" value="{{option.value}}" ng-required="!formulario.tipo" ng-value="true">
                {{option.name}}

                <br>
            </label>

        </div>


        <br>
        <br>


    </form>

    <div>
        <div>
            <button ng-click="myForm()">
                NG-ENVIAR
              
            </button>
        </div>
    </div>
</div>


<div class="col-md-6">
    <div ng-show="showMe">

        <div>

            <respuesta datos="contenedor"></respuesta>

        </div>

    </div>

</div>

Good morning. They sent me to use a code that I already have but without using the $ scope . I'm with Angularjs . I was looking on the Internet but honestly I do not know very well.

Here's the code I have with the $ scope :

angular.module('formApp').controller('formAppCtrl', function ($scope, $http) {

    var vm = this;

    $scope.contenedor = {};
    $scope.contenedor.cantidad = "";
    $scope.contenedor.cuota = "";
    $scope.contenedor.plazos = "";
    $scope.contenedor.tipo ="";

    $scope.formulario = {}
    $scope.formulario.cantidad = 0;
    $scope.formulario.plazos = 0;
    $scope.formulario.tipo = "hipotecario";

    var logresultado = function (respuesta) {
        $scope.contenedor.cantidad = respuesta.cantidad;
        $scope.contenedor.cuota = respuesta.cuota;
        $scope.contenedor.plazos = respuesta.plazos
        $scope.contenedor.tipo = respuesta.tipoCredito;
    };

    $scope.selected = 'Crédito hipotecario';
    $scope.radioOptions = [
       { name: 'Crédito hipotecario', value: 'hipotecario' },

       { name: 'Crédito personal', value: 'personal' },
    ];

    $scope.showMe = false;


    $scope.myForm = function () {

        var baseURL = 'http://localhost:58498/api/cuota?';
        var cantidad = 'cantidad=' + $scope.formulario.cantidad;
        var plazos = '&plazos=' + $scope.formulario.plazos;
        var tipo = '&tipo=' + $scope.formulario.tipo;

        $http.get(baseURL+cantidad+plazos+tipo).success(function (respuesta) {

            console.log(respuesta)
            logresultado(respuesta);

        console.log('entra aqui')
        $scope.showMe = !$scope.showMe;

        })

    }
});

And here the js where I have to implement it but without the $ scope :

    angular.module('App')
        .config(function ($stateProvider) {
            $stateProvider
                .state('solicitud', {
                    url: 'solicitud',
                    controller: 'SolCtrl as sol',
                    templateUrl: '/scripts/app/estados/solicitud/solicitud.html'
                })
        });


    angular.module('App').controller('SolCtrl', solCtrl);

    function solCtrl($http, $scope) {

        var solicitud = this;
        solicitud.name = 'Solicitud //ABANCA';

        function respuestaCtrl() {
            this.solicitud = function () {
                alert('funciona');

            }
        }
};

Thanks in advance !!

    
asked by SilviaGarcia 18.11.2016 в 08:28
source

3 answers

1

If you notice, at the beginning of the controller, you are assigning this to the variable vm.

They will have explained to you what it means and this so I will go to the practical.

So to stop using $ scope, you have to do 2 things:

  • Remove the injection of the $ scope in the controller header (leaving only $ http as dependency).
  • Replace $scope with vm .
  • Also, as an improvement, I suggest the following controller:

    angular.module('formApp').controller('formAppCtrl', function ($http) {
    
    var vm = this;
    
    vm.contenedor = {};
    vm.formulario = {
      cantidad: 0,
      plazos: 0,
      tipo: "hipotecario"
    };
    
    var logresultado = function (respuesta) {
      vm.contenedor = respuesta;
    };
    
    vm.selected = 'Crédito hipotecario';
    vm.radioOptions = [
       { name: 'Crédito hipotecario', value: 'hipotecario' },
       { name: 'Crédito personal', value: 'personal' },
    ];
    vm.showMe = false;
    
    vm.myForm = function () {
    
      var baseURL = 'http://localhost:58498/api/cuota?';
      var cantidad = 'cantidad=' + vm.formulario.cantidad;
      var plazos = '&plazos=' + vm.formulario.plazos;
      var tipo = '&tipo=' + vm.formulario.tipo;
    
      $http.get(baseURL+cantidad+plazos+tipo).success(function (respuesta) {
        console.log(respuesta)
        logresultado(respuesta);
        console.log('entra aqui')
        vm.showMe = !vm.showMe;
      })
    
    }
    

    });

    EDIT: I just found a very complete answer here link

        
    answered by 18.11.2016 / 09:48
    source
    1

    Can you put him in a fiddle? link

    All $scope.variable in the controller should be vm.variable . In the html you have put controller: 'SolCtrl as sol', instead of using variable you should use sol.variable . Try to see and tell me:

    Example:

    angular.module('formApp').controller('formAppCtrl', function ($scope, $http) {
    
      var vm = this;
    
      $scope.contenedor = {};
      $scope.contenedor.cantidad = "";
      $scope.contenedor.cuota = "";
      $scope.contenedor.plazos = "";
      $scope.contenedor.tipo ="";
      // ...
    

    It should be:     angular.module ('formApp'). controller ('formAppCtrl', function ($ scope, $ http) {

      var vm = this;
    
      vm.contenedor = {};
      vm.contenedor.cantidad = "";
      vm.contenedor.cuota = "";
      vm.contenedor.plazos = "";
      vm.contenedor.tipo ="";
      // ...
    

    And in the html for example:

    {{sol.cantidad}} // asignandole algo claro si no te va a salir vacio

        
    answered by 18.11.2016 в 08:57
    1

    To stop using the $scope you just need to associate everything you are now hooking to $scope to the controller itself.

    This can be done simply with this.miDato = 'blabla..' , but since the controller also usually contains functions, and each of them has its own context (a this different), what is usually done is to put var vm = this to the controller's whole beginning, and use vm in all the sites where you now use $scope .

    I leave here a fiddle where you can see it:

    link

        
    answered by 18.11.2016 в 09:59