1

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>

3 Answers 3

2

Your controller declaration is incomplete

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

Working plunker

Sign up to request clarification or add additional context in comments.

Comments

0

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"
    }
});

Comments

0
<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}}"
    })

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.