微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – Angularjs:Controller被多次调用

出于某种原因,当我在资源1和资源2之间切换时,我的控制器被双重调用.

这是代码

的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=preview

如果单击项目1然后单击2,您将看到“资源调用”打印3次:资源之间每次更改2次.

任何线索为什么会发生这种情况?

解决方法

发现一个完全相同的问题:

AngularJs: controller is called twice by using $routeProvider

解决方案是在路由器URL的末尾添加“/”:

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

原文地址:https://www.jb51.cc/js/154542.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐