Set $ scope value of a Controller from an Angular Directive

2

I'm trying to get an object from a Controller from an event in a directive, the controller's method call is already correct, but it seems like $scope within this method is wrong , since if $scope.file.data from the call of the event of the Directive it even arrows the value, but does not update the View , already ifto $scope.file.data from the event of ng-click in div of Controller, everything happens as expected.

What I am trying is the following:

var app = angular.module('myApp', []);

app.controller('myController', function($scope) {
  $scope.file = {
    data: "nada!"
  };
  $scope.setExternal = function(data) {
    console.log(data);
    $scope.file.data = data;
  };
});

app.directive('myDirective', function() {
  return {
    restrict: 'A',
    scope: {
      setOnClick: '&'
    },
    link: function(scope, element, attrs) {
      element.on("click", function() {
        scope.setOnClick({
          param: "Clicou na directive!"
        });
      });
    }
  };
});
body {
  margin: 0px;
}
.box {
  padding: 25px 0px;
  border: 2px dashed #bbb;
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
  border-radius: 5px;
  text-align: center;
  font: 20pt bold'Vollkorn';
  color: #bbb;
  margin: 10px 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="myApp">
  <div ng-controller="myController">
    {{file.data}}

    <div class="box" ng-click="setExternal('Clicou na div!')">
      Está é uma Div do controller. Clique aqui!
    </div>
    <div class="box" my-directive set-on-click="setExternal(param)">
      Está é a Directive. Clique aqui!
    </div>
  </div>
</div>

Example also in jsFiddle.

What I can not do to make the call from the Directive:

element.on("click", function() {
    scope.setOnClick({
        param : "Clicou na directive!"
    });
});

have a $scope valid as ng-click of div ?

  

Note: in my real case the event in the Directive is not a simple click , but a slightly more complex process. I used an example with click for didactic and practical purposes.

    
asked by anonymous 30.04.2015 / 19:30

1 answer

1

Just add scope.$apply(); :

element.on("click", function() {
    scope.setOnClick({
        param : "Clicou na directive!"
    });
    scope.$apply();
});

Updated Fiddle

Tip: Use $scope only for passing data between directives . In Angular 2, $scope will be completely modified since many developers use $scope for everything, and end up creating problems that would not exist if they used controllers correctly (remember directive 's controllers ).

Another advantage is that it is much harder to encounter name conflicts and provide better code reusability.

    
30.04.2015 / 21:08