javascript - How to update directives based on service changes? -
i have directive(parent-directive
) containing slider(myslider), on stop
event, call angular $resource
service 2 params , service return object. directives structure:
<parent-directive> <div ui-slider="slider.options" ng-model="myslider" id="my-slider"> <span child-directive-one></span> <span child-directive-two></span> <span child-directive-three></span> <div> <span child-directive-four></child-directive-four> </div> </parent-directive
whenever user drag slider, service called different params , retieve new result, based on need update child directives.
i have in mind 3 ways:
- using ng-model child elements instead directives, binding them on scope of controller in
parent-directive
; - the second one, don't know how it, create controller in
parent-directive
, send , receive data service , sharechild-directives
in order update them. - the last 1 to create state variable in service , update using controller point 1.(see above) , use $watch supervise variable state , when it's changed update
child-directives
.
how should proceed?
please have here see brief code: http://jsfiddle.net/v5xl0dg9/2/
thanks!
ngmodel
intended 2 way binding, i.e. controls allow user interfere value. description, seems display-only components. advise against usingngmodel
.normally child directives require parent. allows them call methods on parent controller. need opposite: parent controller needs call methods on children. can done: children call
registerchild()
method, , parent iterates registered children when needs call them. find implementation cumbersome.services globals/singletons. vote against tying service implementation ui needs.
my advice looks implementation of option 3, parent controller holding data:
1) place data want share child directives in member variable of parent controller:
myapp.directive('parentdirective', ['myservice', function(myservice){ ... controller: function($scope) { ... this.sharedthing = ...; } }]);
the sharedthing
can updated when service returns new data, or other time necessary.
2) have children require parent (just option 2), , watch property:
myapp.directive('childdirectiveone', function() { return { ... require: 'parentdirective', link: function(scope, elem, attrs, parentdirective) { scope.$watch( function() { return parentdirective.sharedthing; }, function(newval) { // new value; // want place in scope } }); } }; });
depending on nature of data, deep watch may required.
Comments
Post a Comment