I am trying to figure out a “preferred” or “angular -way” for sharing properties or states between controllers / directives. There are several ways to implement this, but I want to stick to best practices. Below are some commonplace examples of how this can be implemented:
1. Using $ scope. $ Watch
angular.module('myModule').controller('parentController', ['$scope', function($scope) {
$scope.state = {
myProperty: 'someState';
};
}]);
angular.module('myModule').controller('childController', ['$scope', function($scope) {
$scope.$watch('state.myProperty', function (newVal) {
});
}]);
Edit: Based on the answers below, this is bad practice and should be avoided. It is not tested and places an unwanted DOM dependency.
2. Using $ broadcast
angular.module('myModule').controller('parentController', ['$scope', function($scope) {
var myProperty = 'someState';
$scope.setState = function (state) {
myProperty = state;
$scope.$broadcast('stateChanged', state);
}
}]);
angular.module('myModule').controller('childController', ['$scope', function($scope) {
$scope.$on('stateChanged', function (evt, state) {
}
}]);
Edit: Bad practice, since you need to know the location of the controllers in the DOM in order to determine the weather for using $ broadcast (down the DOM) or $ emit (up the DOM).
3. Use of the service
angular.module('myModule').factory('stateContainer', [function () {
var state = {
myProperty: 'defaultState'
},
listeners = [];
return {
setState: function (newState) {
state.myProperty = newState;
angular.forEach(listeners, function (listener) {
listener(newState);
});
},
addListener: function (listener) {
listeners.push(listener);
}
}
}]);
angular.module('myModule').controller('parentController', ['$scope', 'stateContainer', function($scope, stateContainer) {
$scope.setState = function (state) {
stateContainer.setState(state);
};
}]);
angular.module('myModule').controller('childController', ['$scope', 'stateContainer', function($scope, stateContainer) {
stateContainer.addListener(function (newState) {
});
}]);
, , , . . , № 3 . Java jQuery, .
: . / , require. . , , Angular.