Ashish Mishra
Ashish Mishra

Reputation: 94

controller inside vs outside of directive

First code is working fine when I declare controller outside of my directive but when i put same directive inside(in second code) it stopped showing any result, i might be missing very silly thing, please help me out.

First code:

<html>
<body>
<div ng-app="mainApp" ng-controller="StudentController">
    <student name="Mahesh"></student>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
  var mainApp = angular.module("mainApp", []);

  mainApp.directive('student', function() {
     return{
     restrict : 'E',
     template : "Student: <b>{{student.name}}</b>",

     scope : {
        student : "=name",
            }
        };
  });

  mainApp.controller('StudentController', function($scope) {
        $scope.Mahesh = {};
        $scope.Mahesh.name = "Mahesh Parashar";
  });

</script>
</body>
</html>

Second code:

<html>
<body>
<div ng-app="mainApp" ng-controller="StudentController">
    <student name="Mahesh"></student>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
  var mainApp = angular.module("mainApp", []);

  mainApp.directive('student', function() {
     return{
     restrict : 'E',
     template : "Student: <b>{{student.name}}</b>",

     scope : {
        student : "=name",
            },
    controller: ['StudentController', function($scope) {
        $scope.Mahesh = {};
        $scope.Mahesh.name = "Mahesh Parashar";
        }]
    };
  });

</script>
</body>
</html>

Upvotes: 1

Views: 1001

Answers (1)

Neophile
Neophile

Reputation: 1519

var mainApp = angular.module("mainApp", []);

mainApp.directive('student', function() {
  return{
    restrict : 'E',
    template : "Student: <b>{{student.name}}</b>",
    scope : {
     student : "=name",
    },
    controller: function($scope) {
      $scope.student = {};
      $scope.student.name = "Mahesh Parashar";
   }
};

});




<div ng-app="mainApp">
  <student name="Mahesh"></student>
</div>

Try ,it will work

Pluner

Upvotes: 1

Related Questions