jquery function does not work with routeprovider Angularjs

Asked

Viewed 239 times

4

I’m making a web application with Angularjs and I did this routeprovider for single page

angular.module("app").config(function($routeProvider){
$routeProvider.when("/Proposta", {
templateUrl:"Proposta.html",
controller :"ClienteController"
});

Gee, I got a function jquery to interact with a input of a form on this page proposta.html:

<script type="text/javascript">
$(function() {
  $("#valor1").maskMoney({
    symbol: 'R$ ',
    showSymbol: true,
    thousands: '.',
    decimal: ',',
    symbolStay: true
  });
})

When I’m on the page index and move to the page proposta.html, this function does not work.

3 answers

2

You are running the function maskMoney the moment the page finishes the load (via $()). The jQuery then maps the DOM Object that has the #valor1 ID, and applies the function.

In a second moment, Angular interprets the route mapping /Proposta, and adds the Proposal.html elements to the DOM. The problem is that the jQuery call has already been executed.

Solution: Run the . maskMoney method inside the controller ClienteController, thus ensuring that the proposal.html DOM Elements are already loaded.

  • Thank you Onosendai... It worked!

1

Complementing the above answer, if you create a directive, and inject in your input field, the directive will be executed After the creation of the field, with this the Jquery code will work, I believe this is the simplest and fastest solution to the problem.

1

Inside the Clientecontroller file you can create a function to start all others related to this view. For example:

$scope.initFunctions = function(){
     $("#valor1").maskMoney({
        symbol: 'R$ ',
        showSymbol: true,
        thousands: '.',
        decimal: ',',
        symbolStay: true
     });
}

or

$scope.initFunctions = function(){
   $(document).ready(function(){
     $("#valor1").maskMoney({
        symbol: 'R$ ',
        showSymbol: true,
        thousands: '.',
        decimal: ',',
        symbolStay: true
     });
   });
}

in the Proposal.html file start this function by calling it with ng-init="initFunctions()" that all functions will be loaded.

For some reason Routerprovider along with other modules does not work as expected, a solution I found was to use the angular-ui-router that works with stateProvider.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.