javascript - AngularJS将范围数据从应用控制器传递到指令
问题描述
尝试将一些范围数据从我的应用控制器传递到指令时遇到问题
(function () {
'use strict';
angular
.module('app', [])
.controller('HomeCtrl', ['$http', '$scope', HomeCtrl])
.directive('services', [
function () {
return {
restrict: 'E',
scope: {
testData: '='
},
template:
'<h2 class="service-name">Test: {{testData}}</h2>'
};
}
]);
/**
* Home controller.
* @param {*} $scope
*/
function HomeCtrl($http, $scope) {
$scope.testData = 'name';
}
})();
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="lib/style.css" />
<script src="lib/script.js"></script>
</head>
<body ng-app="app">
<div ng-controller="HomeCtrl">
<services testData="testData"></services>
</div>
</body>
</html>
我的范围“=”变量未定义,testData 我可以使用 {{testData}} 让它在应用程序中呈现,但是当它作为属性传递时,指令没有接收到值。
解决方案
这是您的显示代码示例修改以将范围数据传递给指令。
(function () {
'use strict';
angular
.module('app', [])
.controller('HomeCtrl', ['$http', '$scope', HomeCtrl])
.directive('services', [
function () {
return {
restrict: 'E',
scope: {
testData: '@testData' // ****************** note here
},
template:
'<h2 class="service-name">Test: {{testData}}</h2>'
};
}
]);
/**
* Home controller.
* @param {*} $scope
*/
function HomeCtrl($http, $scope) {
$scope.testData = 'name';
}
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<body ng-app="app">
<div ng-controller="HomeCtrl">
<!-- // ****************** note here -->
<services test-Data="Hello World!"></services>
</div>
</body>
推荐阅读
- python - 从 python 迭代器直接生成子列表的最佳方法
- swift - Xcode 11. SceneDelegate func willConnectTo。不接受带有属性的函数
- r - R:为一组列返回只有一个非 NA 值的行
- graphviz - 当我使用 lightgbm 时,我无法 plot_tree()
- xml - 使用 xquery (basex) 重命名 XML 中的节点
- javascript - 物化滑块打乱了我的图像大小
- python - 从另一个 Python 脚本设置外部变量
- google-cloud-platform - 使用具有抢占式谷歌计算实例的持久谷歌云盘时磁盘损坏的风险?
- java - Do - 使用 Char (Java) 进行条件循环
- android - 以编程方式将主题添加到 Seekbar 会使 Seekbar 消失