Transitioning from angularJS 1.0 to 1.2 has presented a challenge for me when it comes to assigning a controller to a directive with a distinct scope, without explicitly defining the controller in my HTML using ng-controller.
Let's look at this scenario:
var myApp=angular.module('myApp',[])
.controller('parentCtrl',function($scope,$element,$attrs) {
$scope.helloworld = function(){
console.log('hello world from ParentCtrl controller')
}
})
.controller('childCtrl',function($scope,$element,$attrs) {
$scope.helloworld = function(){
console.log('hello world from ChildCtrl controller')
}
})
.directive('ngParent', function() {
return {
controller:'ParentCtrl'
}
})
.directive('ngChild', function() {
return {
controller:'ChildCtrl',
scope:{},
link:function(scope,element,attrs){
}
}
})
And in the HTML:
<body ng-app="myApp" ng-parent>
<button ng-click="helloworld()">Parent Scope click </button>
<div ng-child>
<button ng-click="helloworld()">Child Scope click </button>
</div>
</body>
Currently, both buttons will log "hello world from ParentCtrl controller". However, changing the parameter scope:{} to scope:true in the ngChild directive results in each button calling their respective scopes' helloworld function. Yet, this solution does not create the clean scope I am aiming for.
How can I achieve a clear scope in a directive using angular 1.2, without specifying the controller in my view?
Best regards, Andreas