簡體   English   中英

AngularJS:從控制器內部訪問元素指令的屬性

[英]AngularJS: Accessing an element directive's attributes from within a controller

問題 :傳遞給指令控制器的屬性未評估。 例如,我得到{{ attribute.value }}而不是5

期望的結果 :我的指令的控制器可以從父控制器訪問對象中包含的主鍵。 我需要它來進行API調用,例如MyResource.save({id: attribute});

代碼段

來自HTML的調用指令

<div ng-controller="BoatDetailController as boatCtrl">
  <div class="row">
    <booking-widget boat-id="{{ boatCtrl.boat.id }}"></booking-widget>
  </div>

指示

(function () {
    'use strict';

    angular.
        module('trips').
        directive('bookingWidget', bookingWidget);

    bookingWidget.$inject = [];

    function bookingWidget() {
        return {
            restrict: 'E',
            scope: {
                boatId: '@'
            },
            templateUrl: "/static/app/trips/trips.bookingwidget.template.html",
            controller: 'BookingWidgetController as bookingCtrl'
        }
    }
})();

控制者

(function () {
    'use strict';

    angular.
        module('trips').
        controller('BookingWidgetController', BookingWidgetController);

    BookingWidgetController.$inject = ['Trip', 'Booking', 'Messages', '$scope', '$attrs'];

    function BookingWidgetController(Trip, Booking, Messages, $scope, $attrs) {
        var vm = this;

        vm.boatId = $attrs.boatId;
        ...

        activate();

        //////////////////////////////

        function activate() {
            console.log(vm.boatId);
            //
        }

控制台結果

使用$scope.boatId (記錄一個空白行)

使用$attrs.boatId{{ boatCtrl.boat.id }} (字符串)

回顧 :我的指令的boat-id屬性無法解析。 您能幫我找出解決方法嗎?

您實際上可以創建一個自定義指令,如下所示:

function bookingWidget() {
        return {
            restrict: 'E',
            scope: {
                boatId: '@'
            },
            templateUrl: "/static/app/trips/trips.bookingwidget.template.html",
            controller: 'BookingWidgetController as bookingCtrl',
            link : function(scope, element, attrs, controller){
               console.log(attrs.boatId);
               scope.boatId = attrs.boatId;
            }
        }
    }

鏈接功能實際上允許您訪問元素,指令的范圍,與指令相關聯的屬性以及指令的控制器。 與指令關聯的所有操作都已執行后,將調用該函數。 換句話說,這是最后一個階段。

鏈接功能和控制器之間可以共享相同的作用域。

現在,要進行API調用,您實際上可以在控制器中添加一個函數,該函數可以接受boatID,對API進行調用,並接受對控制器對象的響應。 之后,在鏈接函數中添加一個監視程序,該監視程序監視“ vm.boatId”,您可以在其中調用該函數以進行API調用。 因此,即使控制器已在鏈接功能之前進行了初始化,您仍然可以執行所需的操作。 因此,這將是“基於鏈接的激活”。

您可以嘗試此解決方案。 希望能幫助到你。

您可以傳遞一個函數並調用它。 需要使用然后。

https://thinkster.io/egghead/isolate-scope-am

暫無
暫無

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

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