问题描述
采用了棱角分明我创造了这样的指令:
角
.module(我的模块,[])
.directive('myDirective',函数(){ 返回{
限制:'E',
templateUrl:('JS','的.html')currentScriptPath.replace,
范围: {
场景:'='
},
控制器:MyDirectiveController,
controllerAs:虚拟机,
bindToController:真实,
替换:真
} });
MyDirectiveController
:
MyDirectiveController $注射='$范围'];功能MyDirectiveController($范围){
VAR VM =这一点;
vm.scenarios = $ scope.scenarios;
}
我的指令HTML模板是这样的:
< DIV> {{vm.scenarios [0]。名称}}< / DIV>
在我父视图HTML我使用的指令是这样的:
<我的指导性方案=vm.scenarios>< /我-指令>
父控制器有一个属性:
vm.scenarios = [] //可能是[{名称:测试}]
由于 vm.scenarios
父控制器得到一个$ HTTP调用它不可设置后,当 vm.scenarios
指令控制器绑定到 $ scope.scenarios
并没有更新的时候,父母控制 vm.scenarios
最终得到填充。
在此添加到我的指令的控制器,它的工作原理,但解决方案似乎我错了:
$范围。$腕表('方案',函数(newValue)以{
如果(为newValue!==未定义){
vm.scenarios = $ scope.scenarios;
}
});
这是你应该如何定义你的指令的控制器:
MyDirectiveController $注射= [];功能MyDirectiveController(){
// 这里没有什么
}
您不需要使用 $范围
,因为你已经绑定到控制器实例这个
。这意味着,范围配置
范围:{
场景:'='
},
填充控制器实例这个
对象,而不是 $范围
对象,因此 $范围.scenarios
是未定义
。随着 vm.scenarios = $ scope.scenarios;
控制器中你只是简单地覆盖正确的未定义值绑定。
演示:
Using Angular I created a directive like this:
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;
}
My directive HTML template is this:
<div>{{vm.scenarios[0].name}}</div>
In my parent view HTML I'm using the directive this way:
<my-directive scenarios="vm.scenarios"></my-directive>
The parent controller has a property:
vm.scenarios = [] // could be [{ name : "test"}]
As the vm.scenarios
of the parent controller gets set after an $http call it is not available when the vm.scenarios
of the directive controller is bound to the $scope.scenarios
and it doesn't get updated when the parents controller vm.scenarios
gets populated eventually.
When adding this to my directives controller, it works but the solution seems wrong to me:
$scope.$watch('scenarios', function(newValue) {
if (newValue !== undefined) {
vm.scenarios = $scope.scenarios;
}
});
This is how you should define your directive controller:
MyDirectiveController.$inject = [];
function MyDirectiveController() {
// nothing here
}
You don't need to use $scope
because you already bind to controller instance this
. It means that scope config
scope: {
scenarios: '='
},
populates controller instance this
object, not $scope
object, and hence $scope.scenarios
is undefined
. With vm.scenarios = $scope.scenarios;
in controller you just overwrite correct binding with undefined value.
Demo: http://plnkr.co/edit/lYg15Xpb3CsbQGIb37ya?p=preview
这篇关于AngularJS指令,ControllerAs,范围和VM财产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!