在AngularJS的指令中使用表达式来表示控制器名(ng-controller)



不使用ng-controller指定控制器名称,我想通过指令中的属性指定控制器名称,然后在模板中替换它(我想用这种奇怪的方式来探索AngularJS)。

这是链接到plunk: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的任何想法?我确定我没有完全理解指令的概念,所以我犯了一个错误?

我推荐这样的结构:

<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

相关内容

最新更新