簡體   English   中英

AngularJS:從具有隔離范圍的控制器中的指令中調用函數

[英]AngularJS : Calling a function in a directive from a controller with isolated scope

我有一條指令,它實際上只是一個具有多個參數的搜索框。 在控制器中,搜索功能需要訪問名為getOptions()的功能,該功能用於獲取搜索框設置。 目前,我通過使用默認scope: false並在指令中使用$scope.getOptions() = function()....進行此工作。

這是一個示例代碼片段(我前面沒有代碼,所以我在記憶中,這在語法上可能不是正確的,但確實可以)

angular.module('example', [])
  .controller('Controller', ['$scope', function($scope) {
  function search() {
    //do something using $scope.getOptions()
  }
  // other functions that modify $scope.someParameter1 ....
  }])
  .directive('searchBox', function() {
    return {
      restrict: 'E',
      templateUrl: 'someurl.html'
      link: link
    };

    function link($scope) {
      $scope.someParameter1 = something;  // the default
      $scope.someParameter2 = something;  // the default
      $scope.getOptions() = function () {
        //do something with parameters
      }
    }
  });

但是,這是一種不好的做法,並且如果我在同一頁面上有多個搜索框,那么它將不起作用,因此我嘗試使用使用scope: {}的隔離范圍。 我可以將參數保留在控制器中,然后將其傳遞到getOptions()函數中,而不是依賴於$scope屬性,但是我不知道如何從控制器中調用getOptions() 我無法從控制器中移動getOptions() ,因為它會在指令中調用多個函數。

謝謝。

您不能直接從孤立的范圍中調用方法,但是我們可以撤消過程。 我們將觀察傳遞給指令的其他屬性的變化。

指令概念證明

.directive('box', function() {
    return {
        scope: {
            outsideScope: '=box'
        },
        template: 'directive box <br> isolated method: {{ wasCalled }}',
        restrict: 'A',
        link: function(scope, element, attrs) {
            scope.$watch('outsideScope', function(newValue, oldValue) {
                if(newValue !== oldValue) {
                    try {
                        scope[newValue](); // I'm going to call method with the name as passed string from controller
                    } catch(e) {
                        console.error(e);
                    }     
                }
            });
            scope.wasCalled = 'wasnt called';
            scope.isolateMethod = function() {
                scope.wasCalled = 'was called';
            }
        }
    }
});

控制器部分

controller('foo', function foo($scope) {
    $scope.changeOutsideScope = function() {
        $scope.outsideScope = 'isolateMethod';
    }
});

的HTML

<div ng-controller="foo">
    <button ng-click="changeOutsideScope()">Call</button>
    <div class="directive" box="outsideScope"></div>
</div>

*您可以在測試中使用,因為Angular提供了.isolateScope()方法,您可以調用已編譯元素來檢索指令范圍。

jsfiddle: http : //jsfiddle.net/krzysztof_safjanowski/P8ajy/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM