Sharing scope between controller & directive in AngularJS

后端 未结 2 393
天命终不由人
天命终不由人 2020-12-30 11:28

I\'ve created a directive to wrap a jQuery plugin, and I pass a config object for the plugin from the controller to the directive. (works)

In the config object is a

相关标签:
2条回答
  • 2020-12-30 12:11

    There are a number of scope issues at work in your demo. First , within the dateChange callback, even though the function itself is declared inside the controller, the context of this within the callback is the bootstrap element since it is within a bootstrap handler.

    Whenever you change angular scope values from within third party code , angular needs to know about it by using $apply. Generally best to keep all third party scopes inside the directive.

    A more angular apprroach is to use ng-model on the input. Then use $.watch for changes to the model. This helps keep all the code inside the controller within angular context. Is rare in any angular application not to use ng-model on any form controls

     <input type="text"  class="datepicker" datepicker="" ng-model="myDate">
    

    Within directive:

    dateInput.bind('changeDate',function(){
          scope.$apply(function(){
             scope[attrs.ngModel] = element.val()
          });
    });
    

    Then in Controller:

    $scope.$watch('myDate',function(oldVal,newVal){ 
           if(oldVal !=newVal){
               /* since this code is in angular context will work for the hide/show now*/
                $scope.dateChanged=true;
                 $timeout(function(){
                       $scope.dateChanged=false;
                  },5000);
            }        
    });
    

    Demo: http://jsfiddle.net/qxjck/10/

    EDIT One more item that should change is remove var dateInput = angular.element('.datepicker') if you want to use this directive on more than one element in page. It is redundant being used in directive where element is one of the arguments in the link callback already, and is instance specific. Replace dateInput with element

    0 讨论(0)
  • 2020-12-30 12:31

    The changeDate event bound to the input seems to be set up to fire outside of the Angular framework. To show the paragraph, call $scope.$apply() after setting dateChanged to true. To hide the paragraph after the delay, you can use $apply() again inside the function passed to setTimeout, but you're likely to keep out of further trouble using Angular's $timeout() instead.

    Fiddle

    0 讨论(0)
提交回复
热议问题