Question

I have this plunkr: http://plnkr.co/edit/vuN0zVhXNMHUEPMeRvRg?p=preview In this plunkr, I call a directive which gets the function "test" from parent scope using the "&" operator. Why when I try to use the function, it returns "undefined"?

HTML:

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.2.x" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p my-directive>Hello {{name}}!</p>
  </body>

</html>

JS:

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

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.test = function test(){
    alert('y');
  }
  console.log(angular.noop);
  console.log($scope.test);
});


app.directive('myDirective', [
    function () {
      return {
        restrict: 'EAC',
        scope: {
          value: '@', // some value
          test: '&' // the function
        },
        link: function(scope, element, attrs) {
          function functionName(func) {
            var ret = func.toString();
            ret = ret.substr('function '.length);
            ret = ret.substr(0, ret.indexOf('('));
            return ret;
          }
          console.log(scope.test());
        }
      };
    }
  ]);
Était-ce utile?

La solution

When you use isolated scope, you are defining a link between the parent scope and the directive scope through attributes when the directive is declared.

So, this code:

scope: {
          value: '@', // some value
          test: '&' // the function
        },

Is saying, "look for an attribute named value and test on the element on which the directive is declared."

So, it is expecting this:

  <body ng-controller="MainCtrl">
    <p my-directive value="{{value}}" test="test()">Hello {{name}}!</p>
  </body>

For documentation see the "Isolating the Scope of a Directive" section of the directive documentation.

Autres conseils

Davin is absolutely right.

This would work exactly like you expect it, (alert pops up) when you use the remove the scope defined on the directive.

Here is your plunker fork: http://plnkr.co/edit/5T9ysjGPBfrhQXRuDGZA?p=preview that works.

By default the scope of a directive is inherited from the controller it is in; but by defining the scope attribute on the directive, you have created an "isoloated scope" that doesn't inherit from the controller.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top