首页 > 解决方案 > AngularJS将变量传递给指令

问题描述

我必须在 AngularJS 应用程序中创建一些指令,并且我需要将变量从我的控制器传递给指令。

问题是我必须使用一种对我来说不常见的指令语法,而且我不知道我必须在指令中用这种语法在哪里声明我的变量。

这是我的指令:

angular
.module('thermofluor')
.directive('tablePlate', tablePlate)

tablePlate.$inject = ['$timeout', '$q'];

function tablePlate( $timeout, $q )
{
var directive = {
    link: link,
    restrict: 'E',
    template: '<h1>TEST</h1>'
};

return directive;

function link(scope, element ) {

    return;

}

}

有人有想法吗?

谢谢。

标签: angularjsangularjs-directiveangularjs-scopedirective

解决方案


// 查看此代码示例以了解如何使用指令

// directive example
angular.module('thermofluor').directive('tablePlate', function(){
return {
    restrict: 'E',
    scope: {
        arrayOfChecks: '='
    },
    template: '<h1>TEST</h1>' + htmlTable,
    link:  function(scope, element, attrs, ctrl){

    }
}
});

var htmlTable = 
'<table>' +
'   <tr>' +
'       <th>Name</th>' +
'       <th>Value</th>' +
'       <th>Active</th>' +
'   </tr>' +
'   <tr ng-repeat="c in arrayOfChecks">' +
'       <td>{{c.name}}</td>' +
'       <td>{{c.value</td>' +
'       <td><input type="checkbox" ng-model="c.active"></td>' +
'   </tr>' +
'</table>';

// controller
angular.module('thermofluor').controller('myController',  function(){
$scope.myListOfChecks = [{name: 'A', value:'A value', active: false},
                    {name: 'B', value:'B value', active: true},
                    {name: 'C', value:'C value', active: false},
                    {name: 'D', value:'D value', active: true}];
});

// html

<div class="row" ng-controller="myController">

<table-plate array-of-checks="myListOfChecks"></table-plate>

</div>

推荐阅读