Scope true in directive giving wrong result

62 views Asked by At

I am using scope as 'true' in a directive. So now, this directive scope passes from parent to child, but not in reverse. I am printing now scope.name 2 times. First in parent scope, second in directive. Now I should get 2 different values. But, I am getting same scope value for both. Pl help explain!

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

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

//app declaration
app.directive('myStudent',function(){

return{
 template: "{{name}}",
 scope:true
}
controller: [function(){
 $scope.name = "Roger"
}]

});
<body ng-app="myApp" ng-controller="myCtrl"> 

{{name}}, 

<my-student></my-student> 

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

3

There are 3 answers

3
tanmay On BEST ANSWER

Your controller is out of directive. I placed it inside and added $scope dependency. It works!

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

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

//app declaration
app.directive('myStudent',function(){

return{
 template: "{{name}}",
 scope:true,
        controller: ['$scope', function($scope) {
            $scope.name = "Roger"
        }]
}


});
<body ng-app="myApp" ng-controller="myCtrl"> 

{{name}}, 

<my-student></my-student> 

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

3
Sai On

Write your controller inside of DDO.

//app declaration
app.directive('myStudent',function(){

return{
    template: "{{name}}",
    scope:true,
    controller: ['$scope', function($scope){
        $scope.name = "Roger"
    }]
}

Probably, this will solve your problem.

0
Vikash Kumar On

Easy make an object in parent controller so that it can be binded with directive i.e var x={}; x.value=value;// that you want to pass then try accessing it.