【问题标题】:How to pass $scope variable from controller to directive using angularjs如何使用 angularjs 将 $scope 变量从控制器传递到指令
【发布时间】:2021-02-07 19:44:01
【问题描述】:

我做了一个简单的指令来打印一个对象:

var app = angular.module("myApp", []);

app.controller('myCtrl', function($scope) {

$scope.users=[
{name:'davidi',age:'23'},
{name:'karen',age:'43'},
{name:'lior',age:'22'}
];

});


app.directive("appCustomer", function() {

var htmlcode="<p ng-repeat='user in customerInfo'>{{user.name}}</p>\
";


return {
restrict: 'E',
scope: {
    customerInfo: '=info'
  },   
template : htmlcode
};
});

我的html代码:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="myCtrl">

<app-customer info="users"></app-customer>

</div>


</body>
</html>


<script src="angularapp.js"></script>

我想简单地访问我的指令中的 $scope.users,以打印没有 ng-repeat 的用户对象, 所以我做到了:

var app = angular.module("myApp", []);

app.controller('myCtrl', function($scope) {

$scope.users=[
{name:'davidi',age:'23'},
{name:'karen',age:'43'},
{name:'lior',age:'22'}
];

});


app.directive("appCustomer", function() {

var htmlcode="";
var userslength=3;


for(var i=0;i<userslength;i++)
{
    htmlcode=htmlcode+"<p>{{users["+i+"]['name']}}</p>";
}

return {
restrict: 'E', 
template : htmlcode
};
});

这很好,但是当我将 userlength 替换为 $scope.users.length 时,应用程序失败。 所以我的问题是如何从指令中的控制器访问 $scope?

JSFiddle

【问题讨论】:

    标签: javascript html angularjs angularjs-directive


    【解决方案1】:
    1. 需要指定link函数

    app.directive("appCustomer", function() {
    
      function link(scope, element, attrs) {
    
        var htmlcode = "";
    
        for (var i = 0; i < scope.users.length; i++) {
          element.text(Put your text here);
          // OR
          element.html(Put your HTML here);
    
        }
      }
    
      return {
        restrict: 'E',
        users: '=',
        link: link
      };
    });

    在您将收到users array的范围内

    1. 第二个是您可以使用元素参数将数据放入模板。或者单独创建html模板

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多