gregwinn gregwinn - 3 months ago 19
AngularJS Question

Update scope from a directive on mousedown Angularjs

I am having an issue updating the scope in a controller from a directive. Below are the basics of what is going on.

myApp.directive('myDirective', ['$document', function($document) {
return {
link: function(scope, element, attr, controller) {
angular.element(element).bind('mousedown', function(event){
scope.name = 'test';
});
}
}
}


myApp.controller('myController', ['$scope', function($scope){
$scope.name = 'something';
}]);


The html:

<p>{{name}}</p>
<p my-directive>Click me</p>


The result above is always
something
that was set in my controller, and is never updated to
test
.

I have tried a
$watch
in my controller but it never updates, so i have to be just missing something...

Lex Lex
Answer

Since you are using jQuery .bind functionality you have to use scope.$apply to notify Angular that you have updated a scope property.

angular.module('app', [])
  .directive('myDirective', function() {
    return {
      restrict: 'A',
      link: function(scope, element, attrs) {
        angular.element(element).bind('mousedown', function(event) {
          scope.$apply(function() {
            scope.name = 'test';
          });
        });
      }
    }
  })
  .controller('ctrl', function($scope) {
    $scope.name = 'something';
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <p>{{name}}</p>
  <p my-directive>Click Me</p>
</div>

Comments