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

时间:2016-01-29 16:42:50

标签: javascript angularjs angularjs-directive

要点:

我试图从视图控制器的$范围中获取一个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永远不会进入视图。当我检查元素并查看指令的属性时,我看到了

后-ID =&#34; mainCtrl.idOfPost&#34;

因为我打电话来在主视图的控制器中获取id,并使用&#39; ctrl将其绑定到控制器。语法,我看到我需要在指令中注意它,因为主视图的控制器将返回一个承诺:请参阅ref:Directive is being rendered before promise is resolved

嗯,这对我没有用。但是,我确实发现使用watch方法并将指令包装在ng-if中会起作用:

<div ng-if="main.idOfPost">
  <foo  post-id="mainCtrl.idOfPost" ></foo>
</div>

然而,这似乎没有必要在视图中使用这样的逻辑并使指令更难使用。我只是不确定如何在js中解决它。任何建议表示赞赏。

4 个答案:

答案 0 :(得分:0)

我遇到了类似的问题。尝试使用带有函数的$ watch来返回范围值

scope.$watch(function(){
    return scope.postId;
}, function(){  //whatever });

由于$ promise在绑定后得到满足,因此可能会导致指令出现​​问题。如果这不起作用,请向Plunker上传一个示例,我会看看。

另外,我认为你应该用双卷曲插入你的指令值

<foo post-id="{{mainCtrl.idOfPost}}"></foo>

而不是

<foo post-id="mainCtrl.idOfPost"></foo>

希望这有帮助

答案 1 :(得分:0)

我会在你的控制器中包含你的idOfPost的初始值

_this.idOfPost = '';

你的指令链接中的$ watch函数应该作为第一个参数,一个函数返回你想要观察的变量:

link: function(scope, element, attr) {
   scope.$watch(
       function() { return scope.postId;},
       function(newVal,oldValue) {
             if(newVal!==oldValue) {   postId = newVal; }
  });

答案 2 :(得分:0)

您可能需要做的是在指令的$scope.$watch而不是controller中实施link,然后关闭您需要的任何其他http来电在那里观看回调。

这是一个基本设置的plnkr:http://plnkr.co/edit/pUybxobHYI6vvjd0M5ON?p=preview

答案 3 :(得分:0)

唯一一个足够接近我的是@ Paul147的建议。但是,我还有一个指令正在使用的过滤器,它引起了更难以弄清楚的更深层次的问题。所以我决定通过ui-router加载视图之前解析数据的全新选项。现在就像魅力一样,没有$ watch!

这是我从中拾取的地方。 https://scotch.io/tutorials/making-skinny-angularjs-controllers