首页 > 解决方案 > 如何使用 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 的用户对象,所以我这样做了:

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
};
});

那工作正常,但是当我替换userlengthto$scope.users.length时,应用程序失败。所以我的问题是如何从指令中的控制器访问 $scope?

JSFiddle

标签: javascripthtmlangularjsangularjs-directive

解决方案


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

推荐阅读