使用角,我创建了这样一个指令:
angular
.module('my-module', [])
.directive('myDirective', function () {
return {
restrict: 'E',
templateUrl: currentScriptPath.replace('.js', '.html'),
scope: {
scenarios: '='
},
controller: MyDirectiveController,
controllerAs: 'vm',
bindToController: true,
replace: true
}
});MyDirectiveController
MyDirectiveController.$inject = ['$scope'];
function MyDirectiveController($scope) {
var vm = this;
vm.scenarios = $scope.scenarios;
}我的指示HTML模板如下:
<div>{{vm.scenarios[0].name}}</div>在我的父视图HTML中,我以这种方式使用该指令:
<my-directive scenarios="vm.scenarios"></my-directive>父控制器具有一个属性:
vm.scenarios = [] // could be [{ name : "test"}]由于父控制器的vm.scenarios是在$http调用后设置的,因此当指令控制器的vm.scenarios绑定到$scope.scenarios时不可用,并且在最终填充父控制器vm.scenarios时不会更新。
当将它添加到我的指令控制器中时,它可以工作,但是解决方案对我来说似乎是错误的:
$scope.$watch('scenarios', function(newValue) {
if (newValue !== undefined) {
vm.scenarios = $scope.scenarios;
}
});发布于 2015-07-11 13:53:22
这是您应该如何定义您的指令控制器:
MyDirectiveController.$inject = [];
function MyDirectiveController() {
// nothing here
}您不需要使用$scope,因为您已经绑定到控制器实例this。这意味着范围配置
scope: {
scenarios: '='
},填充控制器实例this对象,而不是$scope对象,因此$scope.scenarios是undefined。在控制器中使用vm.scenarios = $scope.scenarios;,您只需用未定义的值覆盖正确的绑定。
演示: http://plnkr.co/edit/lYg15Xpb3CsbQGIb37ya?p=preview
https://stackoverflow.com/questions/31357698
复制相似问题