簡體   English   中英

將對象上下文從AngularJS指令傳遞回控制器回調

[英]Pass object context back to controller callback from AngularJS Directive

我本質上是在嘗試重新創建ng-change,但在其中添加了一些延遲(更改頻率超時時自動保存)。

到目前為止,我有以下指令:

myApp.directive('changeDelay', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        require: 'ngModel',
        scope: {
            callBack: '=changeDelay'
        },
        link: function (scope, elem, attrs, ngModel) {
            var firstRun = true;
            scope.timeoutHandle = null;

            scope.$watch(function () {
                return ngModel.$modelValue;
            }, function (nv, ov) {
                console.log(firstRun);
                if (!firstRun) {
                    console.log(nv);
                    if (scope.timeoutHandle) {
                        $timeout.cancel($scope.timeoutHandle);
                    }
                    scope.timeoutHandle = $timeout(function () {
                        //How can I pass person??
                        scope.callBack();
                    }, 500);
                }
                firstRun = false;
            });
        }
    };
}]);

使用以下控制器:

myApp.controller('MyCtrl', ['$scope', function ($scope) {
    $scope.people = [{
        name: "Matthew",
        age: 20
    }, {
        name: "Mark",
        age: 15
    }, {
        name: "Luke",
        age: 30
    }, {
        name: "John",
        age: 42
    }];

    $scope.updatePerson = function (person) {
        //console.log("Fire off request to update:");
        //How can I get person here??
        //console.log(person);
    };

}]);

並且此標記應該能夠定義要調用的控制器作用域方法以及傳遞給它的對象:

<div ng-app='myApp'>
    <div ng-controller="MyCtrl">
        <div ng-repeat="person in people">
            <input type="text" ng-model="person.name" change-delay="updatePerson(person)" />
        </div>
    </div>
</div>

這是一個失敗的小提琴: http : //jsfiddle.net/Troop4Christ/fA4XJ/

如您所見,我不知道如何調用帶有傳遞給它的“ person”參數的指令屬性參數。

因此,就像我說的那樣,在一開始..只是嘗試通過一些“調整”來重新創建ng-change。 如何在ng-change中完成?

隔離范圍綁定應使用“&”而不是“ =”聲明,從而導致scope.callBack()執行給定的updatePerson(person)函數。

說明

隔離范圍時,可以使用“ @”,“ =”和“&”:

  • “ @”告訴angular觀看針對元素范圍的屬性評估結果
  • “ =”告訴angular使用$parse構建getter / setter
  • “&”告訴angular綁定一個將評估屬性的函數(並作為選項,提供對屬性定義范圍的擴展,作為此函數調用的參數)。

因此,當您選擇最后一個選項“&”時,意味着在isolate指令作用域上調用callBack()實際上將再次調用updatePerson(person)外部作用域(不使用來自隔離作用域的任何對象擴展)。

考慮到范圍擴展功能,您可以通過調用scope.callBack({person: {a:1}})來替換updatePerson(person)person參數。 那么person將在updatePerson調用范圍(函數范圍,而不是angular scope )中成為{a:1}

暫無
暫無

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

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