[英]How to pass $scope variable from controller to directive using angularjs
我做了一個打印 object 的簡單指令:
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 ,打印用戶 object 而不使用 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
時,應用程序失敗。 所以我的問題是如何從指令中的 controller 訪問 $scope?
link
function 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 }; });
在 scope 中,您將收到users array
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.