麻烦将参数从指令传递给控制器

时间:2015-06-30 14:02:40

标签: javascript angularjs

我遇到将参数从指令传递给控制器​​的问题。参数" compoundID"不断回来未定义。我使用角js。我打算每页有一个以上的指令。

JS:

angular.module('ireg').directive('compound', function () {
return {
    restrict:'E',
    scope:{             
        compoundID:'='
    },
    templateUrl: '/ireg/components/compound/compound.html'
};
});

angular.module('ireg').controller("compoundController",['$scope','$attrs','compoundService', function($scope,$attrs,compoundService ){
    var vm = this;
    vm.compoundID = $attrs.compoundID;
    console.log($attrs);
}]);

HTML:

<div class = "compound-view" ng-controller = "compoundViewController as controll" > 
<compound compoundID="{{controll.compoundID}}"></compound>{{controll.compoundID}}
<div = "studies" ng-repeat="study in controll.studies">
    <studie studyID="{{study.ID}}"></studie>
</div>
<cro croID= "{{croID}}"></cro>

1 个答案:

答案 0 :(得分:2)

如果你宣布这样的范围:

scope:{             
    compoundID:'='
},

您只是告诉compoundID属性应被视为由Angular自动解析的模型。您应该直接使用该模型,而不是:

<compound compoundID="{{controll.compoundID}}">

写道:

<compound compoundID="controll.compoundID">

如果你想写<compound compoundID="{{controll.compoundID}}">,你的范围应该像这样声明:

scope:{             
    compoundID:'@'
},

同时请注意Angular将您的指令定义中的aSampleAttribute(“驼峰案例”)翻译为a-sample-attribute(em ...“kebab case ?? ??) HTML。所以我认为,如果您在指令中compoundID可能必须写<compound compound-i-d="………">

我知道这很讨厌,所以我建议你使用...... compoundId =&gt;而是compound-id