在我的自定义指令中,为了设置正确的模板,我需要能够使用像这样传递的参数:
ng-click="loadTabContent('socialnetwork')"
在我的控制器中,我有这样的内容:
$scope.loadTabContent = function(passedArgument){
$scope.content = PostsResource.query();
// below I'd like to attach the above argument onto $scope object like so
$scope.networkCalled = passedArgument;
}
然后在我的指令中,我会这样做:
// linker function
var linker = function(scope, element, attrs){
// does NOT work
element.html( getTemplate(scope.networkCalled) );
// does work, provided I have type="somename" on my directive element in HTML
element.html( getTemplate(attrs.somename) );
$compile( element.contents() )(scope);
}
我怀疑参数的值没有及时附加到$scope对象,所以当我需要它时它不可用。$apply或任何其他内置函数应该解决这个问题吗?
编辑:我相信我的指令中遗漏了一个重要的部分:
return {
restrict: "A",
replace: true,
link: linker,
scope: {
content: '='
}
如果我理解正确,您将指令scope.networkCalled
与控制器的scope属性绑定。不幸的是,那时angular 还没有更新它的绑定。
当您使用隔离作用域时,请记住声明您的networkCalled
属性:
scope: {
content: '=',
networkCalled:'='
}
并在html中绑定属性:
<div your-directive network-called="networkCalled"></div>
尝试$watch在绑定更新时获得通知:
var linker = function(scope, element, attrs){
scope.$watch("networkCalled",function (value){
if (value){
element.html( getTemplate(value) );
$compile( element.contents() )(scope);
}
});
}
AngularJS:指令不能访问隔离作用域对象