javascript - 如何使用 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
};
});
那工作正常,但是当我替换userlength
to$scope.users.length
时,应用程序失败。所以我的问题是如何从指令中的控制器访问 $scope?
解决方案
- 您需要指定
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
- 第二个是您可以使用元素参数将数据放入模板。或者单独创建html模板
推荐阅读
- listview - Xamarin:使用 MVVM 的分组 ListView 不绑定删除命令
- expressiveannotations - 将模型的属性用于 requiredif 语句而不将其放入实际的 DOM
- xml - 使用 F# XMLProvider 解析带有命名空间的 XML
- javascript - Javascript:使用第一个属性对对象数组进行排序,并在与另一个属性相等时排序
- php - 通过 php 变量使用 getElementById
- jenkins - Kubectl 删除但忽略有错误的
- node.js - ReferenceError:当我推送 Heroku 时未定义要求
- asp.net - asp.net 代码生成器不断要求包,即使它已经添加
- codeigniter - HTML5 视频播放器问题 PHP
- java - 存储为字符串的两次之间的差异