Search code examples
javascriptangularjsangularjs-scopeangular2-directives

Scope true in directive giving wrong result


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> 


Solution

  • 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>