[英]AngularJS Passing Scope Data From App Controller to Directive
尝试将一些范围数据从我的应用程序控制器传递给指令时遇到问题
(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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.