$watch inside a service?

前端 未结 4 1250
轻奢々
轻奢々 2020-12-13 01:47

Is it possible to set up a $watch on an array of objects inside a service (I\'d like the $watch declaration itself to be inside the service)?

4条回答
  •  有刺的猬
    2020-12-13 02:25

    Hey just had a situation where I had a pretty big watch setup on 2 different controllers.

    As I didn't want to duplicate any code I just defined to function in my service :

    angular
        .module('invoice')
        .factory('invoiceState', function () {
            var invoice = {
                client_info: {
                    lastname: "",
                    firstname: "",
                    email: "",
                    phone: "",
                    id_client: "",
                    ... 
                 }
            }
            invoice.watchAccommodation = function (newVal, oldVal) {
                var accommodation = newVal;
                //Whatever you would normally have in your watch function
            }
    

    Then I can just call this function in the watch of any controller into which I injected the service

    function NewInvoiceCtrl(invoiceState) {
        $scope.$watch('invoice.accommodation',invoiceState.watchAccommodation, true);
    }
    

    I do not have much experience with AngularJS so I can't really go into the performance aspects of this approach but it works ;)

提交回复
热议问题