如何使用 angularjs 将 $scope 变量从控制器传递到指令

How to pass $scope variable from controller to directive using angularjs

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

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

  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模板