[英]AngularJS Directive binding to controller
我试图找出 AngularJS 指令。 我有以下 JSFiddle 和一个我正在尝试做的事情的例子。 https://jsfiddle.net/7smor9o4/
正如您在示例中看到的,我希望vm.alsoId
变量等于vm.theId
。 在模板中vm.theId
显示了正确的值,但vm.alsoId
没有。
我究竟做错了什么? 我怎样才能实现我的目标。
如果它有帮助,最后的想法是执行以下操作:
function directive(service) {
var vm = this;
vm.entity = null;
init();
function init() {
service.getEntity(vm.theId).then(function (entity) {
vm.entity = entity;
});
}
}
Angular 建议您“仅当您想将 API 公开给其他指令时才绑定控制器。否则使用链接”。
这是使用链接功能的工作小提琴。
angular.module('app', [])
.directive('directive', directive);
angular.element(function() {
angular.bootstrap(document, ['app']);
});
function directive() {
return {
restrict: 'E',
scope: {
theId: '<'
},
template: `
alsoId: <span ng-bind="alsoId"></span>
theId: <span ng-bind="theId"></span>`,
link: link
};
}
function link(scope, element, attrs) {
init();
function init() {
scope.alsoId = scope.theId;
}
}
正如您所注意到的, bindToController
绑定在控制器的构造函数中不是立即可用的(与$scope
不同,后者是)。 您正在寻找的是 Angular 1.5 引入的一项功能: Lifecycle Hooks ,特别是$onInit
。
你的想法是对的; 只需按如下方式替换您的init
函数定义和调用:
vm.$onInit = function () {
service.getEntity(vm.theId).then(function (entity) {
vm.entity = entity;
});
};
这是您更新的小提琴。 (或者,如果没有此解决方案,您将需要watch
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.