Creating a JSFiddle with Angular-ui-router and mul

2019-07-08 06:24发布

问题:

I have a question I would like to ask the community, but am having trouble setting up the required JSFiddle to make it easier to demonstrate the issue. I want to create a fiddle with three views side by side using Angular's ui-router. Seems simple, but for some reason I can't get the views' controller's to initialize. The main app loads, as evidenced by console messages, but I'm stumped.

The Fiddle is here, and for completeness sake, the html and js are here:

HTML:

<div ui-view="top" class="top">
  <br />
  $scope.testmsg = {{testmsg}}
  <br />
  $scope.statename = {{statename}}
  <br />
  top!
</div>
<div ui-view="middle" class="middle">middle!</div>
<div ui-view="bottom" class="bottom">bottom!</div>

JS:

/* myApp module */
var myApp = angular.module('myApp', ['ui.router'])
.config(['$stateProvider', function ($stateProvider) {

$stateProvider.state('home', {
    url: "/",
    views: {
        'top': {
            url: "",
            template: '<div>top! {{topmsg}}</div>',
            controller: function ($scope) {
                $scope.topmsg = "loaded top!";
                console.log("top ctrl!"); // this does NOT show in console
            }
        },
        'middle': {
            url: "",
            template: '<div>middle! {{middlemsg}}</div>',
            controller: function ($scope) {
                $scope.middlemsg = "loaded middle!";
                console.log("middle ctrl!"); // this does NOT show in console
            }
        },
        'bottom': {
            url: "",
            templateUrl: '<div>bottom! {{bottommsg}}</div>',
            controller: function ($scope) {
                $scope.bottommsg = "loaded bottom!";
                console.log("bottom ctrl!"); // this does NOT show in console
            }
        }
    },
    onEnter: function () {
        console.log("entered home state"); // this does NOT show in console
    }
  });
}])
.controller('MyAppCtrl', function ($scope, $state/*, $stateParams*/) {
  $scope.statename = $state.current.name;
  $scope.testmsg = "app scope working!";
  console.log("MyAppCtrl initialized!"); // this shows in console
  $state.go("home");
});

My body tag has the correct (I believe) references to my app and controller: <body ng-app="myApp" ng-controller="MyAppCtrl"></body>... I'm stuck. Any help would be great.

Thanks in advance!

回答1:

I think your only mistake is in the configuration for the 'bottom' view. You have templateUrl instead of template. After I made this change in your fiddle, all the controllers initialize correctly.

Here's an updated fiddle. But like I said, changing templateUrl to template is the only change. Hope this helps!