简体   繁体   English

ng-controller和ui-view在同一元素上不起作用

[英]ng-controller and ui-view doesn't work on the same element

I am using AngularJS and ui-router. 我正在使用AngularJS和ui-router。 My code has ng-controller and ui-view on the same element and the controller doesn't get triggered 我的代码在同一元素上具有ng-controller和ui-view,并且不会触发控制器

http://plnkr.co/edit/UphvqV01R7m0WwlY67YA?p=preview http://plnkr.co/edit/UphvqV01R7m0WwlY67YA?p=preview

HTML: HTML:

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

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link href="style.css" rel="stylesheet" />
    <script data-semver="1.2.7" src="http://code.angularjs.org/1.2.7/angular.js" data-require="angular.js@1.2.x"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.0/angular-ui-router.js"></script>

    <script src="app.js"></script>
  </head>

  <body>
    <div ui-view="main" ng-controller="MainCtrl">
      <p>Hello {{name}}!</p>  
    </div>

  </body>

</html>

Javascript: Javascript:

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

app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider) {
  $stateProvider
    .state("home", {
      url: "^",
      resolve: {
        test: function() {
          alert("Triggered resolve home");
          return true;
        }
      }
    })
}]);

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

Can you help to fix it or explain why? 您能帮助解决它或解释原因吗?

You need to have your main module ultimately dependent on 'ui.router' somehow. 您需要使主模块最终以某种方式依赖于'ui.router' Right now you have it dependent on nothing ( [] ). 现在,您不依赖任何内容( [] )。

var app = angular.module('plunker', ['ui.router']);

Don't do this. 不要这样

When you transition to a state, ui.router assigns a controller to each active uiView element, so any controller you had previously assigned would be replaced. 当您转换到状态时, ui.router会为每个活动的uiView元素分配一个控制器,因此将替换您之前分配的任何控制器。

Just wrap the uiView in a parent element and apply the controller to that. 只需将uiView包装在父元素中,然后将控制器应用于该元素。

Also, as Words Like Jared has pointed out, you're not even importing the ui.router module, so you need to do that, too. 而且,正如Jared所说的那样,您甚至都没有导入ui.router模块,因此您也需要这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM