ng-controller and ui-view doesn't work on the same element
-
23-12-2019 - |
Question
I am using AngularJS and ui-router. My code has ng-controller and ui-view on the same element and the controller doesn't get triggered
http://plnkr.co/edit/UphvqV01R7m0WwlY67YA?p=preview
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:
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?
Solution
You need to have your main module ultimately dependent on 'ui.router'
somehow. Right now you have it dependent on nothing ([]
).
var app = angular.module('plunker', ['ui.router']);
OTHER TIPS
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.
Just wrap the uiView
in a parent element and apply the controller to that.
Also, as Words Like Jared has pointed out, you're not even importing the ui.router
module, so you need to do that, too.