【问题标题】:AngularJS - Updating variables within the parent controller scope from a function in a transcluded directive scopeAngularJS - 从嵌入指令范围内的函数更新父控制器范围内的变量
【发布时间】:2015-03-05 07:02:23
【问题描述】:

如何从嵌入指令范围的函数中更新父控制器范围变量?

我通过以下方式使用嵌入将指令嵌入到另一个指令中:

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

my-table 和 my-getter-button 的代码如下:

my-table模板:

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

my-table 指令:

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

my-getter-button 指令(带模板):

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
    };
});

我期待 scope.$parent.instance = data; // or scope.instance = data; 更改父控制器的 scope.instance,但它没有。

【问题讨论】:

    标签: javascript angularjs transclusion angularjs-ng-transclude


    【解决方案1】:

    我为自己的问题找到了解决方案。 原来我需要的是一个 setter 函数。 我在控制器中添加了以下内容:

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

    并调用了setter函数(而不是进行赋值操作),如下:

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

    它更新了父控制器范围内的变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-06
      相关资源
      最近更新 更多