简体   繁体   中英

AngularJS - Updating variables within the parent controller scope from a function in a transcluded directive scope

How are parent controller scope variables updated from within a transcluded directive scope's function?

I am embedding directives into another directive using a transclusion in the following manner:

<my-table>
  <my-getter-button></my-getter-button>
</my-table>

The code for my-table and my-getter-button follows:

my-table template:

<table>
  <tr ng-repeat="item in items">
    <td data-id="{{item.Id}}" ng-transclude></td>
  </tr>
</table>

my-table directive:

.directive('myTable', function () {
      return {
          transclude: true,
          restrict: 'E',
          templateUrl: 'views/mytable.html',
          scope: false
      };
  });

my-getter-button directive (with template):

app.directive('myGetterButton', function () {
    function link(scope, element) {
        scope.finalizeGet = function () {
            var id = element.parent().data('id');
            scope.clear();  // <-- works fine (from parent controller)
            scope.get(id)  // <-- works fine (from parent controller)
            .success(function (data) {
                // The line below was supposed to 
                // update the variables within the parent controller:
                scope.$parent.instance = data; // or scope.instance = data;
                angular.element('#detailsModal').modal('show');
            })
            .error(function (data) {
                scope.errors = data;
            });
        };
    };

    return {
        restrict: 'E',
        template: '<button class="btn btn-info" ng-click="finalizeGet()">' +
                      '<span class="glyphicon glyphicon-book"></span>' +
                  '</button>',
        scope: false,
        link: link
    };
});

I was expecting scope.$parent.instance = data; // or scope.instance = data; scope.$parent.instance = data; // or scope.instance = data; to change the parent controller's scope.instance but it did not.

I found a solution for my own problem. Turns out what I needed was a setter function. I added the following in my controller:

// Set current model instance of scope.
$scope.setInstance = function(data) {
  $scope.instance = data;
};

And called the setter function (instead of having an assignment operation), as follows:

// ...
.success(function (data) {
  scope.setInstance(data);
  angular.element('#detailsModal').modal('show');
})
// ...

It updated the variable in the parent controller scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM