Deadpool
Deadpool

Reputation: 8240

Passing scope in template of a directive - AngularJs

I am trying to set in scope in directive and get it printed. But its giving error. Can someone help?

//module declaration 
var app = angular.module('myApp',[]);

//controller declaration
app.controller(function($scope){
$scope.name = "Joseph";
});

//app declaration
app.directive('myStudent',function(){
return{
	template: "Hi! Dear!! {{name}}"
}
});
<body ng-app="myApp" ng-controller="myCtrl"> 

   <my-student></my-student> 
   <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script> 

</body>

Upvotes: 1

Views: 215

Answers (3)

Adrian Zelada Torrez
Adrian Zelada Torrez

Reputation: 92

<body ng-app="myApp" ng-controller="myCtrl"> 


 <my-student></my-student> 
   <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script> 

</body>

app.controller("myCtrl", ["$scope", function($scope){
    $scope.name="Adrian":
}]);

in directive

app.directive('myStudent',function(){
    return{
      scope:'=',
      template: "Hi! Dear!! {{name}}"
})

or

<body ng-app="myApp" ng-controller="myCtrl"> 


     <my-student name="name"></my-student> 
       <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script> 

    </body>

and your directive :

app.directive('myStudent',function(){
    return{
          scope:{
              name:'=',
          },
          template: "Hi! Dear!! {{name}}"
    })

Upvotes: 0

Tom Johnson
Tom Johnson

Reputation: 689

You need to declare your controller properly via;

app.controller("myCtrl", ["$scope", function($scope){

$scope.name = "Joseph";
}]);

And you need to tell your directive to use this controller via;

app.directive('myStudent',function(){
    return{
        template: "Hi! Dear!! {{name}}",
        controller: "myCtrl"
    }
});

Upvotes: 0

ndoes
ndoes

Reputation: 678

Your controller declaration is incomplete

//controller declaration
app.controller('myCtrl', function($scope){
    $scope.name = "Joseph";
});

Working plunker

Upvotes: 2

Related Questions