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

梦想与她 提交于 2019-12-18 12:54:21

问题


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.


回答1:


Use $apply method:

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

Explanation: How does data binding work in AngularJS?



来源:https://stackoverflow.com/questions/19154539/angular-js-how-to-update-the-scope-from-a-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!