This thread follow angularjs share data config between controllers
so I'm wondering if instead of copy by hand property/method is it safe doing like
.factory('MyTest',function(){
return {
prop: 'Mytest',
myFunc: function(){
alert('Hello');
}
}
})
.controller('IndexCtrl', function ($scope,MyTest) {
angular.extend($scope,MyTest);
console.log($scope);
})
Update It works of course only for property but if it's safe could be a good thing find a way to apply it also for method.
UPDATE 1
This seems to be a good way:
'use strict';
(function(window, angular, undefined) {
'use strict';
angular.module('ctrl.parent', [])
.controller('ParentController',function (scope) {
scope.vocalization = '';
scope.vocalize = function () {
console.log(scope.vocalization);
};
});
})(window, angular);
angular.module('app',['ctrl.parent'])
.controller('ChildCtrl', function($scope,$controller){
angular.extend($scope, new $controller('ParentController', {scope:$scope}));
$scope.vocalization = 'BARK BARK';
});
credit to @marfarma
UPDATE 2
I'm wondering why this doesn't work
'use strict';
angular.module('animal', [])
.factory('Animal',function(){
return function(vocalization){
return {
vocalization:vocalization,
vocalize : function () {
console.log('vocalize: ' + this.vocalization);
}
}
}
});
angular.module('app', ['animal'])
.factory('Dog', function (Animal) {
function ngPost() {};
ngPost.prototype.status = ['publish','draft'];
return angular.extend(Animal('bark bark!'), new ngPost());
})
.factory('Cat', function (Animal) {
return Animal('meeeooooow');
})
.controller('MainCtrl',function($scope,Cat,Dog){
$scope.cat = Cat;
$scope.dog = Dog;
console.log($scope.cat);
console.log($scope.dog);
//$scope.cat = Cat;
});
this works
.factory('Dog', function (Animal) {
function ngDog(){
this.prop = 'my prop';
this.myMethod = function(){
console.log('test');
}
}
return angular.extend(Animal('bark bark!'), new ngDog());
})
UPDATE 3
sorry to bother you again but after a while thinking of this thread I think my question was misunderstood (or I didn't explain myself clearly) what I wanted really know if doing like
angular.extend($scope,MyService)
could be bad/good practice is it breaking oop encapsulation principle ? I mean it smells like
MyService.call($scope);
and you could face variable and function conflicts
so .......
You can have a look at the source of the
extend
function and see it's safe: