17

How can I update scope in directive?

<div ng-controller="MyCtrl">
    <p t></p>
</div>

My directive:

var myModule = angular.module('myModule', [])
    .directive('t', function () {
        return {
            template: '{{text}}',
            link: function (scope, element, attrs) {
                scope.text = '1';
                element.click(function() {
                     scope.text = '2';
                });
            }
        };
    })
    .controller('MyCtrl', ['$scope', function ($scope) {
    }]);

After click directive does not update.

myusuf
  • 11,810
  • 11
  • 35
  • 50
ExyTab
  • 527
  • 3
  • 7
  • 14

1 Answers1

43

Use $apply method:

  element.click(function() {
      scope.$apply(function(){
           scope.text = '2';
      });
  });

Explanation: How does data binding work in AngularJS?

Community
  • 1
  • 1
Ivan Chernykh
  • 41,617
  • 13
  • 134
  • 146