12

http://plnkr.co/edit/Rf0VItthVBg6j0z7KudO

I'm using a jQuery dialog and want to use the dialog buttons, but I don't know how to get at the scope to trigger a (currently non-existent) $http or $resource call back to the server with the updated model when the jQuery dialog button is clicked. I feel as if I'm going about this wrong, but I don't know what direction to go here.

2 Answers 2

23

You can use Angular functions to find the scope attached to an element and call a function on it. I prefer to really abstract it away and find the root of the ng-app and broadcast an event into the app so that the outside-code doesn't know about the specifics of the inside code except for the event that you broadcast.

angular.$externalBroadcast = function (selector, event, message) {
    var scope = angular.element(selector).scope();

    scope.$apply(function () {
        scope.$broadcast(event, message);
    });
};

Then, from any code, you can call something like:

angular.$externalBroadcast('#app-container', 'doSomething', parameters);

And inside the app, I'd do something like this:

$rootScope.$on('doSomething', function(parameters) {
    // handle the external event.
});

If you don't like this approach, just get the scope:

var scope = angular.element(selector).scope();

And do something with it. Just make sure you call scope.$apply or else the digestion cycle won't happen.

Sign up to request clarification or add additional context in comments.

2 Comments

In the above situation is there a way to get a factory or a directive scope?
Nvm. It seems that the scope you get is the rootScope. I attached the service to the root scope and was able to call it just how i needed. Thanks for this!
4

Best way is to add directive to control. It is a bad idea to add jQuery with angularjs along side. Directive are made to do this kind of manipulation.

Here's I have modified your plunkr to show you what you can do with directives.

app.directive('date', function() {
  return {
     restrict: 'A',
     require: '^ngModel',
     link: function(scope, elm, attrs, ctrl) {
       var dp = $(elm);

       dp.datepicker({
         onSelect: function(dateText) {
           scope.$apply(function() { // Apply cause it is outside angularjs
            ctrl.$setViewValue(dateText); // Set new value of datepicker to scope
           });
        }
       });

       scope.$watch(attrs.ngModel, function(nv) {
         dp.datepicker('setDate', nv); // Update datePicker date when scope change
       });
     }
  }

1 Comment

My question has nothing to do with the date picker and is all about the buttons you can add to the jQuery dialog being able to call a controller scope method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.