Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
756 views
in Technique[技术] by (71.8m points)

function called twice inside angularjs controller

I am new to angular js and currently stuck with very wired kind of a bug. function in a controllers runs twice when its called by view loaded against a route.

http://jsfiddle.net/4gwG3/5/

you will see alert twice!!

my view is simple

and my app code is following

var IB = angular.module('IB', []);    

//channel controller
IB.controller('channelsController', function ($scope, $routeParams) {
    $scope.greet = function () {
        alert('hi');
    };
});


IB.config(function ($routeProvider) {
    $routeProvider
    .when('/channels', {
        controller: 'channelsController',
        template: '{{greet()}}'
    })

    .otherwise({ redirectTo: '/channels' });

});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First check that you're not initializing your Angular app twice (by having it initialized automatically with ng-app).

One time I had 2 html pages with ng-app (one for login.html and another for main.html) and this was a problem I realized later.

Second and for me the most important, check if you have attached your controller to multiple elements. This is a common case if you are using routing.

In my case I was navigating to DashboardController like so:

app.config(function($routeProvider){
    $routeProvider
    .when('/', {
        controller: 'DashboardController',
        templateUrl: 'pages/dashboard.html'
    })
});

But I also had this in dashboard.html:

<section class="content" ng-controller="DashboardController">

Which was instructing AngularJS to digest my controller twice.

To solve it you have two ways:

removing ng-controller from your html file like this:

<section class="content">

or removing controller from routing (that is normally situated in app.js):

app.config(function($routeProvider){
$routeProvider
        .when('/', {
            templateUrl: 'pages/dashboard.html'
        })
    });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...