为什么我的整数没有从我的 AngularJs 指令中插值
Why is my integer not being interpolated from my AngularJs Directive?
摘要:
我正在尝试从视图控制器的$scope中获取一个 id,并将其传递给我的指令,然后使用该 id 进行更多的 http 调用。
这是我的控制器和指令 js:
app.controller('MainCtrl', function(postsFactory) {
_this = this;
postsFactory.get({ id: $state.params.id}).$promise.then(function(res){
//assign the response to this controller as a post and
//output the controller on the view as editPostCtrl.
_this.post = res;
_this.idOfPost = _this.post.id;
// the post.id does exist
});
});
app.directive('foo', function() {
return {
restrict: 'E',
scope: {
postId: '=postId',
},
controller: function($scope) {
//make some more http calls with the postId
},
link: function(scope, element, attr) {
scope.$watch('postId', function(newVal) {
if(newVal) { postId = newVal;}
});
}
};
});
观点:
<body ng-controller="MainCtrl as mainCtrl">
<foo post-id="mainCtrl.idOfPost"></foo>
</body>
问题:
该 id 永远不会进入视图。当我检查元素并查看指令的属性时,我看到
post-id="mainCtrl.idOfPost"
由于我调用了主视图控制器中的 id 并使用"ctrl as"语法将其绑定到控制器,因此我看到我需要在指令中监视它,因为主视图的控制器将返回一个 promise:请参阅此参考: 指令在解析承诺之前呈现
好吧,这对我不起作用。但是,我确实发现使用 watch 方法并将指令包装在 ng-if 中会起作用:
<div ng-if="main.idOfPost">
<foo post-id="mainCtrl.idOfPost" ></foo>
</div>
但是,这似乎没有必要在这样的视图中具有逻辑,并使指令更难使用。我只是不确定如何在 js 中解决它。任何建议不胜感激。
我遇到了类似的问题。 尝试将$watch与函数一起使用以返回范围值
scope.$watch(function(){
return scope.postId;
}, function(){ //whatever });
由于$promise是在绑定后完成的,因此可能会导致指令出现问题。 如果这不起作用,请将示例上传到 Plunker,我会看看。
另外,我认为您还应该用双卷曲插入指令值
<foo post-id="{{mainCtrl.idOfPost}}"></foo>
而不是
<foo post-id="mainCtrl.idOfPost"></foo>
希望这有帮助
我会在你的控制器中包含你的idOfPost的初始化值
_this.idOfPost = '';
指令链接中的$watch函数应该具有第一个参数,一个返回您想要监视的变量的函数:
link: function(scope, element, attr) {
scope.$watch(
function() { return scope.postId;},
function(newVal,oldValue) {
if(newVal!==oldValue) { postId = newVal; }
});
要做的是在指令的controller
而不是link
中实现$scope.$watch
,然后触发您需要在该监视回调中执行的任何其他http调用。
这是一个具有基本设置的 plnkr:http://plnkr.co/edit/pUybxobHYI6vvjd0M5ON?p=preview
对我来说足够接近的是@Paul147的建议。但是,我还有一个指令正在使用的过滤器,它导致了更深层次的问题,真的很难弄清楚。因此,我决定采用一个全新的选项,在视图通过ui-router加载之前解析数据。现在就像一个魅力,没有$watch!
这是我从哪里捡到的。https://scotch.io/tutorials/making-skinny-angularjs-controllers
- 为什么ngModelCtrl$脏不在我的指令中更新
- 为什么我的指令(使用链接)没有出现,并允许ng模型看到它
- 我的指令在ngRepeat和ngInclude之前执行,尽管默认优先级为0
- 为什么我的指令是't使用ng-bind-html指令
- 为什么可以't我的指令从其父作用域继承函数
- 我的指令没有开火
- ng-change在我的指令中不适用于选择
- 为什么我的指令中的值没有传递到函数中
- 如何使用角度将属性发送到我的指令
- 角度JS:如何延迟加载我的指令
- 我在从我的指令 Angular 访问控制器的范围时遇到问题
- 如何将数据库中的 html 标签注入到我的指令的模板中,实际上是动态定义模板的根元素/标签
- AngularJS:为什么我的指令作为ng-class指定的类不被识别
- 如何确保ng repeat在我的指令检查表格之前填写表格
- 为什么在我的指令中使用ng repeat会对我的绑定产生影响
- 为什么这个索引中的1+1出现在我的指令中
- 为什么获胜'我的指令对其作用域变量进行插值
- 在我的指令中获取$last和$parent
- 为什么我的指令没有出现
- 为什么不'在我的指令中点击工作,以及如何添加切换类