问题
I have a controller that needs to get some info from a component. Each are getting created by angular through the dom. I understand that components update the models that are given to them which can be provided by the controller. What is the angular way to notify the controller about those changes in the component?
回答1:
To say that you want a controller to be notified about a change from a component isn't really the correct way to think about what is going on.
In the controller, some type of data model is represented and projected to a view using the current $scope of the controller. When a DOM element (component I'm assuming from your terminology) wants to update the model that the controller is providing, that model is bound via a directive (commonly ng-model) to a component. When that component changes the model, the data is updated automatically because of the directive and the data binding.
回答2:
See docs
//$scope.$watch(<function/expression>, <handler>);
$scope.$watch('foo', function(newVal, oldVal) {
console.log(newVal, oldVal);
});
Also of interest:
$scope.$on()
$scope.$emit()
$scope.$broadcase()
$scopt.$watchCollection()
来源:https://stackoverflow.com/questions/21415998/what-is-the-standard-way-to-send-messages-between-ngcontroller-and-ngcomponent-i