search

Home  >  Q&A  >  body text

angular.js - How to isolate '&' in scope using AngularJS?

‘@’ and ‘=’ are easy to understand. Is there a scenario where ‘&’ must be used?

<body ng-app="myApp" ng-init="content='abc'">
<p ng-controller="myController" >
    <input type="text" ng-model="content" />
    <p my-directive my-title="title" my-content="content" ></p>
</p>
</body>
<script type="text/javascript">
var myApp = angular.module('myApp', [])
.directive('myDirective', function($rootScope) {
    return {
        priority:1000,
        restrict: 'A',
        replace: true,
        scope: {
            myTitle:'@',
            myContent: '='
        },
        template: '<p><h2>{{myTitle}}</h2><p>from myDirective:{{myContent}}</p></p>'
    };
})  
.controller('myController',function($scope){
    $scope.content = 'from controller';
});
</script>

I hope you can provide a demo.

怪我咯怪我咯2756 days ago747

reply all(1)I'll reply

  • phpcn_u1582

    phpcn_u15822017-05-15 16:52:53

    Usage of

    &: Pass a function from the parent scope to be called later

    When to use it: When we need to call a controller method in a directive, we usually pass some parameters in the directive to the controller method

    Actual case: For example, in a tree-structured directive, after we select a node, we need to perform further operations on this node in the controller, such as fetching data from the server based on the selected node. So in the directive, we need to pass the selected node to the controller.

    Demo

    Demo code:

    javascriptangular.module('docsIsoFnBindExample', [])
    .controller('Controller', ['$scope', '$timeout', function($scope, $timeout) {
      $scope.name = 'Tobias';
      $scope.message = '';
      $scope.hideDialog = function (message) {
        $scope.message = message;
        $scope.dialogIsHidden = true;
        $timeout(function () {
          $scope.message = '';
          $scope.dialogIsHidden = false;
        }, 2000);
      };
    }])
    .directive('myDialog', function() {
      return {
        restrict: 'E',
        transclude: true,
        scope: {
          'close': '&onClose'
        },
        templateUrl: 'my-dialog-close.html'
      };
    });
    
    html<p ng-controller="Controller">
      {{message}}
      <my-dialog ng-hide="dialogIsHidden" on-close="hideDialog(message)">
        Check out the contents, {{name}}!
      </my-dialog>
    </p>
    



    my-dialog-close.html:

    <p class="alert">
      <a href class="close" ng-click="close()">&times;</a>
      <p ng-transclude></p>
    </p>
    

    reply
    0
  • Cancelreply