Joel Blum
Joel Blum

Reputation: 7878

Angular Binding In Partials

I am using the Angular seed (download from angular webpage) and am trying to display data from scope's controller inside the partial . this is the code :

app.js

'use strict';
// Declare app level module which depends on filters, and services
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives',      'myApp.controllers']).
  config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller:   'mainPage'});
  $routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});
   $routeProvider.otherwise({redirectTo: '/view1'});

   }]);

controllers.js

'use strict';

 /* Controllers */

angular.module('myApp.controllers', []).
controller('mainPage', ['$scope',function() {

  $scope.data= "this is my data";
}])
  .controller('MyCtrl2', [function() {

 }]);

index.html

<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8">
<title>My AngularJS App</title>
<link rel="stylesheet" href="css/app.css"/>
</head>
<body>
<ul class="menu">
<li><a href="#/view1">view1</a></li>
<li><a href="#/view2">view2</a></li>
</ul>

<div ng-view></div>
... some more angular includes etc

partial1.html

<p>This is the partial for view 1. {{data}}</p>

I was expecting to see the data defined in the controller , however I simply see : "This is the partial for view 1. {{data}}"

Upvotes: 0

Views: 338

Answers (2)

Craig Squire
Craig Squire

Reputation: 2141

I think the main problem is you're not passing $scope into the controller function. You should have gotten an error on your browser console. See the working Plunker here:

http://plnkr.co/edit/ItziGeIVI5a9L56P1UCx

var myApp = angular.module('myApp', []).
  config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view1', {templateUrl: 'partial1.html', controller:   'mainPage'});
  $routeProvider.when('/view2', {templateUrl: 'partial2.html', controller: 'MyCtrl2'});
   $routeProvider.otherwise({redirectTo: '/view1'});

   }]);

myApp.controller('mainPage', ['$scope',function($scope) {
  $scope.data = "this is my data";
}])
.controller('MyCtrl2', ['$scope', function($scope) {
  $scope.data = "this is my data 2";
}]);

Upvotes: 2

Buu
Buu

Reputation: 50345

This:

controller('mainPage', ['$scope', function() {
  $scope.data= "this is my data";
}])

Should be:

controller('mainPage', ['$scope', function($scope /* ADD THIS */) {
  $scope.data= "this is my data";
}])

Upvotes: 1

Related Questions