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

问题描述

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

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的users对象, 所以我做到了:

var app = angular.module("myApp",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. 第二个是您可以使用element参数将数据放入模板中。或单独创建html模板