簡體   English   中英

將對象(變量)傳遞給指令angularjs

[英]Pass object (variable) to directive angularjs

控制器在狀態下被調用。

.controller('test', function($scope) {
    $scope.variable = 'Hello';
    $scope.other = 'Hi';
})
.directive('customDir', function() {
    return {
        restrict: 'A',
        link: function($scope, element, attrs) {
            attrs.customDir += ' Word';
        }
    }
});

<input type="text" custom-dir="variable" />
<div>{{variable}}</div>

<input type="text" custom-dir="other" />
<div>{{other}}</div>

我需要$ scope.variable和$ scope.other接收“Word”,必須能夠在Directive中更改傳遞變量的值。

有幾種方法。 第一個是使用雙向綁定:

.directive('customDir', function() {
    return {
        scope: {customDir: '='},
        link: function(scope, element, attrs) {
            scope.customDir += ' Word';
        }
    }
});

演示: http //plnkr.co/edit/zQOMttjnbvdf6OJNOeoq?p = preview

如果您不需要新的隔離范圍,則另一個:

.directive('customDir', function() {
    return {
        link: function(scope, element, attrs) {
            scope[attrs.customDir] += ' Word';
        }
    }
});

演示: http //plnkr.co/edit/FmIy3z4t1SEJQn1YQAkP?p = preview

暫無
暫無

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

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