角度属性指令值

Angular attribute directive value

本文关键字:指令 属性      更新时间:2023-09-26

我想直接从属性指令中获取一个值:

 <form cronos-dataset="People as p">
     Form Content
 </form>

在我的JS中,我尝试过:

app.directive('cronosDataset',[function() {
  return {
    restrict: 'A',
    controller: 'CronosGenericDatasetController',
    scope: {
        "cronos-dataset" : '@'
    }
  };
}])
.controller("CronosGenericDatasetController",['$scope', function($scope) {
    alert($scope["cronos-dataset"]);
}]);

我想提醒"People as p"字符串,但我得到了undefined。这是一条正确的道路吗?还是我应该采取一种不同的方法?

您应该在作用域声明中有camelBase

app.directive('cronosDataset',[function() {
  return {
    restrict: 'A',
    controller: 'CronosGenericDatasetController',
    scope: {
        cronosDataset : '@'
    }
  };
}])

这里有一个演示,可以看到不同的变体http://plnkr.co/edit/G6BiGgs4pzNqLW2sSMt7?p=preview

改为创建链接函数:

app.directive('cronosDataset',[function() {
  return {
    scope: {},
    restrict: 'A',
    link: function (scope, elem, attrs) {
        alert(attrs.cronosDataset);
    }