3

i have a demo on plunkr, i have facing problem while click function on ng-click event function calls twice by checking in 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

Satpal
  • 132,252
  • 13
  • 159
  • 168
Nimesh khatri
  • 763
  • 12
  • 29

2 Answers2

5

Oh well, it's simple, you are calling $location.path("/view"); and in the view2.html there is an ng-init doing the same result()function:

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

This is the updated Plunker with one possible (fast) solution.

michelem
  • 14,430
  • 5
  • 50
  • 66
  • Thanks for your help i know that problem in above line but how do i restrict to execute function second time and display result on view2.html if i remove ng-init from view2.html, function executes only once but i'll not get result on view2 .. getting the point ??? – Nimesh khatri Jul 16 '15 at 07:30
  • I think there are many ways, but I don't want to rewrite everything, so just add a new function `clickHere()` that does only the `$location.path("/view")` Here is the updated Plunker http://plnkr.co/edit/PmxLBb9tJ8q7OdGZwfzd?p=preview – michelem Jul 16 '15 at 07:35
  • Hii can you please check belowed link :- http://stackoverflow.com/questions/31451652/getting-null-array-after-redirect-using-location-path-in-angularjs/31451846?noredirect=1#comment50872215_31451846 here my problem is i'm not getting dynamic data .. – Nimesh khatri Jul 16 '15 at 11:21
0

Also you can add simple check for the current location and render different code, Please refer 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);
}

Thanks

Vasimkhan
  • 323
  • 1
  • 11