Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js How to update the scope from a directive?

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.

like image 303
ExyTab Avatar asked Oct 03 '13 08:10

ExyTab


People also ask

What is @? In Angular directive scope?

These prefixes are used to bind the parent scope's methods and properties to the directive scope. There are 3 types of prefixes in AngularJS: '@' – Text binding / one-way binding. '=' – Direct model binding / two-way binding.

What is the difference between the scope of a directive and the scope of a controller?

No difference. It is same object.

Does AngularJS support scope inheritance?

The $scope object used by views in AngularJS are organized into a hierarchy. There is a root scope, and the $rootScope can has one or more child scopes.

What is Transclude in AngularJS directive?

The ng-transclude directive facilitates AngularJS to capture everything that is put inside the directive in the markup and use it somewhere in the directive's template. Syntax: <ng-transclude.


1 Answers

Use $apply method:

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

Explanation: How does data binding work in AngularJS?

like image 83
Ivan Chernykh Avatar answered Sep 18 '22 15:09

Ivan Chernykh