Angularjs:控制器被多次调用 [英] Angularjs: Controller is called multiple times

查看:326
本文介绍了Angularjs:控制器被多次调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某些原因,我的控制器,双叫,当我的资源1 resource2之间切换。

For some reason, my controller is double called, when I switch between resource 1 and resource2.

这里的code:

的index.html

<!DOCTYPE html>
<html ng-app="multiple_calls">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <link rel="stylesheet" href="style.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <a href="#res/1">1</a>
    <a href="#res/2">2</a>

    <div ng-view>
    </div>
  </body>

</html>

app.js

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

app.
  config(['$routeProvider', function($routeProvider) {
  $routeProvider.
      when('/res/:id', {templateUrl: 'res.html',
                        controller: 'res'
      });
}]);


app.controller('MainCtrl', function($scope) {
});

app.controller('res', function($scope, $routeParams) {
  console.log('resource called')
  $scope.id = $routeParams.id;
});

res.html

{{id}}

http://plnkr.co/edit/HsCJmbllOcnlvlc1oiHa?p=$p$ PVIEW

如果您单击项目1,然后2,你会看到资源被称为印3次:2次资源之间的每一个变化

If you click item 1 and then 2, you'll see that "resource called" is printed 3 times: 2 times for each change between resources.

任何线索,为什么出现这种情况?

Any clues why this happens?

推荐答案

找到一个确切的同样的问题:

Found an exact same question:

<一个href=\"http://stackoverflow.com/questions/14442954/angularjs-controller-is-called-twice-by-using-routeprovider\">AngularJs:控制器使用名为两次$ routeProvider

解决的办法是添加/在路由器URL的末尾:

The solution is to add "/" at the end of router url:

-      when('/res/:id',
+      when('/res/:id/',

这篇关于Angularjs:控制器被多次调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆