16

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,053
  • 9
  • 34
  • 49
ExyTab
  • 508
  • 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
  • 40,230
  • 12
  • 130
  • 145