Essentially, there is no distinction between the two methods - both involve adding a watcher to the scope (if they operated differently, it would present an issue!).
In my approach, I typically incorporate watchers in the directive to regulate the mapping of external attributes to internal scope variables (similar to using an isolate scope in directives). Essentially, the controller is indifferent to the source of the values as long as they reside on the scope.
Subsequently, I utilize watchers in the controller to monitor changes in these internal properties and react accordingly within the controller. The directive doesn't concern itself with how the properties are utilized; its main objective is to ensure they are available on the scope for the controller.
Below is an illustration employing an isolate scope:
angular.module('MyModule').directive('myDirective', function(){
return {
scope: {
'internalProp': '=externalProp' // Establishes a watcher on the external property
// and assigns it to `scope.internalProp`
},
controller: function($scope){
$scope.internalProp // Work with `internalProp`, as the directive manages exposing it to the scope.
$scope.$watch('internalProp.myProp', function(value){
// Execute actions upon change in `myProp`.
});
}
};
});
Additionally, here is an example where a child scope is used but still maps the same external value to scope.internalProp
. This manner does not create an isolate scope so that scope inheritance persists (which can prove beneficial in specific scenarios).
angular.module('MyModule').directive('myDirective', function($parse){
return {
scope: true,
link: function(scope, element, attr){
// Demonstrates manual monitoring of attribute values within a directive.
var propGetter = $parse(attr['externalProp']);
scope.$parent.$watch(propGetter, function(value){
scope.internalProp = value;
});
},
controller: function($scope){
$scope.internalProp // Work with `internalProp`, facilitated by the directive exposing it to the scope.
$scope.$watch('internalProp.myProp', function(value){
// Execute actions upon change in `myProp`.
});
}
};
});
In both instances, the directive dictates how external attributes translate to internal scope variables, enabling the controller to interact with those internal properties as necessitated.