在 angularjs 控制器中调用两次的函数 [英] function called twice inside angularjs controller
问题描述
我是 angular js 的新手,目前遇到了一个非常复杂的错误.当控制器中的函数被针对路由加载的视图调用时,它会运行两次.
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.
你会看到两次警报!!
我的观点很简单
my view is simple
我的应用代码如下
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' });
});
推荐答案
首先检查您是否没有将 Angular 应用初始化两次(通过使用 ng-app 自动初始化).
First check that you're not initializing your Angular app twice (by having it initialized automatically with ng-app).
有一次我有 2 个带有 ng-app 的 html 页面(一个用于 login.html 和另一个用于 main.html),这是我后来意识到的一个问题.
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.
就我而言,我是这样导航到 DashboardController 的:
In my case I was navigating to DashboardController like so:
app.config(function($routeProvider){
$routeProvider
.when('/', {
controller: 'DashboardController',
templateUrl: 'pages/dashboard.html'
})
});
但我在dashboard.html中也有这个:
But I also had this in dashboard.html:
<section class="content" ng-controller="DashboardController">
指示 AngularJS 消化我的控制器两次.
Which was instructing AngularJS to digest my controller twice.
解决方法有两种:
像这样从您的 html 文件中删除 ng-controller:
removing ng-controller from your html file like this:
<section class="content">
或从路由中删除控制器(通常位于 app.js 中):
or removing controller from routing (that is normally situated in app.js):
app.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl: 'pages/dashboard.html'
})
});
这篇关于在 angularjs 控制器中调用两次的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!