[英]using expression for controller name(ng-controller) in a directive in AngularJS
而不是使用ng-controller
指定控制器名称,我想通过指令中的属性指定控制器名称,然后在模板中替换它(我想以这种奇怪的方式来做,只是为了探索AngularJS)。
这是小车的链接: http ://plnkr.co/edit/KZgLQ6? p= preview
例如我正在尝试做的事
<sample-drtv ctrl-name="drtvCtrl"></sample-drtv>
模板(sampleDrtv.html):
<div ng-controller="{{ctrlName}}">
<p>{{ptagcontent}}</p>
</div>
指令代码:
var myModule = angular.module('ng');
myModule.directive('sampleDrtv',[function(){
return {
restrict: "E",
replace: true,
templateUrl: "sampleDrtv.html",
scope: {},
controller: function($scope,$element,$attrs){
$scope.ctrlName = $attrs.ctrlName;
console.log($scope);
}
};
}]);
function drtvCtrl($scope){
$scope.ptagcontent = "AngularJS Rocks";
}
我在控制台上收到此错误:
Error: Argument '{{ctrlName}}' is not a function, got undefined
我应该怎么做ctrlName
在表达式中替换ctrlName
任何想法? 我确定我不完全理解指令的概念,所以我做错了吗?
我会推荐这种结构:
<sample-drtv></sample-drtv>
模板(sampleDrtv.html):
<div ng-controller="drtvCtrl">
<p>{{ptagcontent}}</p>
</div>
AngularJS部分:
var myModule = angular.module('ng');
myModule.directive('sampleDrtv',[function(){
return {
restrict: "E",
replace: true,
templateUrl: "sampleDrtv.html"
};
}]);
function drtvCtrl($scope){
$scope.ptagcontent = "AngularJS Rocks";
}
参见Plunk: http ://plnkr.co/edit/GwnqK6?p = preview
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.