Function calls twice in angularjs

I have a demo on plunkr, I have a problem where the click on ng-click function calls the function calls twice, checking the console: -

<a class="btn btn-default finish" style="display:none" ng-click="result()">Finish</a>

      

here is my controller code: -

var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider, $locationProvider) {
    $routeProvider.when('/', {
        templateUrl: 'MainView.html',
        controller: 'MainCtrl'
    }).when('/view', {
        templateUrl: 'view2.html',
        controller: 'MainCtrl'
    });
});
app.controller('MainCtrl', function($scope, $location) {
    $scope.name = 'World';
    $scope.correctAnswer = [];

    $scope.result = function() {
        $scope.correctAnswer.push({
            "label1": "value1"
        }, {
            "label2": "value2"
        }, {
            "label3": "value3"
        });
        console.log($scope.correctAnswer);
        $location.path("/view");
    }
});

      

Plunker

+3


source to share


2 answers


Well, it's simple, you call $location.path("/view");

, and in view2.html

exists ng-init

, performing the same function result()

:

<div class="tab-pane fade" id="profile" ng-init="result()">

      



This is an updated Plunker with one possible (quick) solution.

+5


source


Also you can add a simple check for the current location and render other code, please see below code:

$scope.result = function () {

  if($location.path() == ("/")){ 
     $location.path("/view");
  }else{
    $scope.correctAnswer.push({"label1":"value1"},{"label2": "value2"},{"label3": "value3"});
  }
  console.log($scope.correctAnswer);
}

      



thank

0


source







All Articles