在指令的模板中传递范围 - AngularJs

时间:2016-12-13 12:30:31

标签: javascript angularjs

我正在尝试在指令中设置范围并将其打印出来。但它给出了错误。有人可以帮忙吗?



//module declaration 
var app = angular.module('myApp',[]);

//controller declaration
app.controller(function($scope){
$scope.name = "Joseph";
});

//app declaration
app.directive('myStudent',function(){
return{
	template: "Hi! Dear!! {{name}}"
}
});

<body ng-app="myApp" ng-controller="myCtrl"> 

   <my-student></my-student> 
   <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script> 

</body>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:2)

您的控制器声明不完整

//controller declaration
app.controller('myCtrl', function($scope){
    $scope.name = "Joseph";
});

Working plunker

答案 1 :(得分:0)

您需要通过;

正确声明您的控制器
app.controller("myCtrl", ["$scope", function($scope){

$scope.name = "Joseph";
}]);

你需要告诉你的指令通过;

使用这个控制器
app.directive('myStudent',function(){
    return{
        template: "Hi! Dear!! {{name}}",
        controller: "myCtrl"
    }
});

答案 2 :(得分:0)

<body ng-app="myApp" ng-controller="myCtrl"> 


 <my-student></my-student> 
   <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script> 

</body>

app.controller("myCtrl", ["$scope", function($scope){
    $scope.name="Adrian":
}]);
指令

中的

app.directive('myStudent',function(){
    return{
      scope:'=',
      template: "Hi! Dear!! {{name}}"
})

<body ng-app="myApp" ng-controller="myCtrl"> 


     <my-student name="name"></my-student> 
       <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script> 

    </body>

和你的指令:

app.directive('myStudent',function(){
    return{
          scope:{
              name:'=',
          },
          template: "Hi! Dear!! {{name}}"
    })