我一直在开发一个 AngularJS 指令,它应该作为一个独立的小部件工作,可以通过以对象形式设置属性来配置它。我的主要目标如下:
- 根据传入属性的对象在指令内部进行处理。处理确实涉及获取 REST API 响应。所以我正在使用 Controller 来实现这一点。
- 在我的指令做了一些处理之后,它可能会改变我的父 Controller 应该能够改变的对象。
下面是涵盖我的目标的示例代码。
指令用法:
<post-listing page-id="currentPage.id" config="postConfig" posts="posts" />
指令代码
'use strict';
angular.module('myApp')
.directive('postListing', function () {
return {
templateUrl: '/views/directive.post-listing.html',
restrict: 'EA',
scope: {
page_id:"=",
config:"=",
posts:"=",
},
controller: "DirectivePostListingCtrl"
};
});
指令 Controller 代码:
'use strict';
angular.module('myApp')
.controller('DirectivePostListingCtrl', function ($scope, $rootScope, $routeParams)
{
// Here I want to access the page_id and config as the actual value
// Here I will also update the posts array which is exposed to outside of directive.
});
模板代码:
<h4>Displaying Posts for {{page.title}}</h4>
<ul>
<li ng-repeat="p in posts" >{{p.title}}</li>
</ul>
当我运行这段代码时,它显示 $scope.page_id "undefined" 或 "currentPage.id"(基于运算符 selected = 或 @ ) 我希望它是 currentPage.id 的值。
请提出建议。
提前致谢。
最佳答案
您没有遵循独立范围属性名称的驼峰式命名规则。如果您使用此配置,您将能够访问页面 ID:
scope: {
pageId: "=",
config: "=",
posts: "=",
},
在 Controller 中:
console.log($scope.pageId);
关于javascript - 将动态数据传递给 angularjs 指令的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27646509/