I have one controller used by two different views:
<div ng-controller="MyCtrl" ng-include="slice = false">
<span ng-repeat="value in values">{{ value }}</span>
</div>
...
<span ng-controller="MyCtrl">
<div ng-repeat="value in values">{{ value }}</div>
</span>
The controller:
var MyCtrl = function($scope){
$scope.values = ['a','fancy','array'];
// if called from span
//$scope.values = ['a','fancy','array'].slice(2);
}
I'd like to know if it is possible to detect from what element the controller is being called to change the behavior of the controller.
Update: Based on @matys84pl's answer, here is my new controller
MenuCtrl = function($scope) {
$scope.slice = true;
if($scope.slice === false) { // wont go inside
$scope.data = ['a','fancy','array'];
} else {
$scope.data = ['a','fancy','array'].slice(2);
}
console.log($scope.slice); // still true for both
}
The rule is that the controller should not be aware of the view... so you should instead pass something from the view to the controller using ngInit, like this:
<div ng-controller="MyCtrl">
<span ng-repeat="value in values">{{ value }}</span>
</div>
...
<span ng-controller="MyCtrl" ng-init="isDifferent = true">
<div ng-repeat="value in values">{{ value }}</div>
</span>
and then check isDifferent value in the controller.
Update: A plunker with working example: http://plnkr.co/edit/zUgLSQcAaZX5j6JBoQAO
<div ng-controller="MyCtrl" behavior=2>...
Please forgive my lazy js - I'm used to coffeescript
var MyCtrl = function($scope, $attrs){
if $attrs.behavior != 2
$scope.values = ['a','fancy','array'];
else
$scope.values = ['a','fancy','array'].slice(2);
}
I guess you could do something similar by swapping $attrs for $element and changing your test.