2014-10-27 57 views
0

一个指令内部控制器我是新来的角,并具有以下指令:数据绑定到角

angular.module('myApp') 
    .directive('myDirective', function() { 
    return { 
     templateUrl: '/views/partial-views/partial.html', 
     restrict: 'E', 
     controller : function(){ 
     age : '5' 
     }, 
     controllerAs : 'myCtrl' 
    }; 
    }); 

我想包括内部partial.html我的页面上的年龄,看起来像这样:

<div ng-app="myApp" ng-controller="myCtrl as s"> 
    {{s.age}} 
</div> 

但是我收到以下错误:

Error: [ng:areq] Argument 'myCtrl' is not a function, got Object 

任何人能告诉我什么,我做错了什么?

+0

为什么部分包含'ng-app'?但无论如何,删除'ng-controller'声明并尝试'myCtrl.age' – Chandermani 2014-10-27 02:58:39

+0

这是一个很好的观点,我只是因为它是一个稍微做作的例子。当我没有引用控制器时,我没有收到任何错误,但是当我像{{myCtrl.age}}一样引用时,年龄并未出现在页面上。 – Jamesla 2014-10-27 03:04:47

+0

我不知道为什么甚至不会抛出错误,应该是'this.age = 5'而不是'age:5' – Chandermani 2014-10-27 03:40:57

回答

1

您的代码有两个问题。首先,您不要再次为控制器别名,在模板中使用ng-controller,以便需要删除。

其次,控制器是一个功能不反对,所以使用:

this.age = '5';

2

Chandermani提到什么是绝对正确的。更一种高精度,它可以作为,

指令定义

angular.module('myApp') 
    .directive('myDirective', function() { 
     return { 
      templateUrl: '/views/partial-views/partial.html', 
      restrict: 'E', 
      controller: ['$scope', function($scope){ 
       $scope.age = '5' 
      }] 
    }; 
}) 

使用

<div ng-app="myApp"> 
    <my-directive> 
    {{age}} 
    </my-directive> 
</div> 

然而,有没有在这里定义指令的含义被写入。您可以使用控制器定义来执行相同的操作。