You can have two solution
Solution 1: use '=' in isolated scope, it binds a local/directive scope property to a parent scope property.
.directive('ptest', ['$compile', function($compile) {
var object = {value: 'changed value'};
return {
scope: {
iobj:"="
},
template : "<div>{{iobj.value}}<div>",
link: function(scope,elem,attr){
scope.iobj=object ;
}
};
}]);
in html
<div ng-controller="testCtrl">
<div ptest iobj="object"></div>
</div>
Solution 2: use $controller service and make testCtrl as parent and copy its all scope to controllers scope
.directive('ptest', ['$compile', function($compile,$controller) {
var object = {value: 'changed value'};
return {
controller:function($scope,$controller){
$controller('testCtrl', {$scope: $scope});
console.log($scope.object.value);
$scope.object = object;
}
};
}]);
working example for '=' solution 1 :
angular.module('test',[])
.controller('testCtrl',function($scope){
$scope.object = {value:'intial value'};
})
.directive('ptest', ['$compile', function($compile) {
var object = {value: 'changed value'};
return {
//replace:true,
scope: {
iobj:"="
},
template : "<div>{{iobj.value}}<div>",
link: function(scope,elem,attr){
scope.iobj=object ;
}
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test" ng-controller="testCtrl">
{{object.value}}
<div ptest iobj="object"></div>
</div>
Working example for solution 2 with $controller
angular.module('test',[])
.controller('testCtrl',function($scope){
$scope.object = {value:'intial value'};
})
.directive('ptest', ['$compile', function($compile,$controller) {
var object = {value: 'changed value'};
return {
controller:function($scope,$controller){
$controller('testCtrl', {$scope: $scope});
console.log($scope.object.value);
$scope.object = object;
}
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test" ng-controller="testCtrl">
{{object.value}}
<div ptest ></div>
</div>