为什么我的整数没有从我的 AngularJs 指令中插值

Why is my integer not being interpolated from my AngularJs Directive?

本文关键字:我的 指令 插值 AngularJs 整数 为什么      更新时间:2023-09-26

摘要:

我正在尝试从视图控制器的$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