2015-05-28 101 views
0

我正在使用自定義directive進行導航,當某些添加/刪除該導航中的任何內容時,我想反映該導航上的更改。如果該導航來自範圍,那麼我可以更新範圍,但由於導航來自指令,所以我不知道如何在$http成功上調用該指令。

這裏是我的指令:

<nav_toolbar uuid=\"pk\" my-method=\"get_navs\"></nav_toolbar>

在這裏你可以看到我使用的一些屬性太指令,它可以幫助我獲取準確的導航選項。

指令代碼:

app.directive('synapseToolbar', function() { 
    var controller = ['$scope', '$element', '$attrs', '$http', '$compile','Scopes', 
     function ($scope, $element, $attrs, $http, $compile, Scopes) { 
     var uuid = $scope.uuid 
     // my $http request comes here 
     // on $http success i'll set this below scope  
      $scope.synapse_toolbar_icons = a object 
     }]; 
    return { 
    restrict: 'EA', 
    scope: { 
     uuid: '=', 
     method: '&myMethod', 
    }, 
    controller: controller, 
    link: function (scope, element, attrs) { 
      var click_fn = scope.method(); 
      $(element).click(function(e, rowid) { 
       click_fn(scope.link_source, scope.link_fact_type); 
      }); 
      }, 
    template: '<div ng-show="synapse_toolbar_icons" ng-repeat="toolbar in synapse_toolbar_icons" class="tile iconSizeClass synapse-toolbar bg-crimson ng-scope" data-toggle="tooltip" ng-click="bindData(toolbar.link_source, toolbar.link_fact_type)">'+ 
       '<div dynamic="toolbar.icon_html"></div>'+ 
       '</div>', 
    }; 
}); 

功能上,我想調用指令再次

$scope.remove_synapse_link = function(){ 

     $http({ 
       method : 'POST', 
      }).success(function(data,status){ 
       // here I want to call that directive again 
      }) 
      .error(function(data,status){ 
        $.notify("Something went wrong while adding dislike", "error"); 
      }); 
    } 

Plunkerhttp://plnkr.co/edit/FpzGkIpBPfOnoFrwQkmj?p=preview

+0

我認爲你需要使用$ watch函數。你能提供指令和控制器代碼嗎? – jme11

+0

請問您可以添加您的指令代碼嗎? –

+0

@pankajparkar指令添加 – saf

回答

10

$http返回一個承諾,是異步的。您的指令在您的html呈現時運行。所以你所做的就是在你得到響應之前不要渲染HTML。

HTML:

<div ng-if="ready"> 
    <div my-custom-directive></div> 
</div> 

控制器:

$scope.ready = false;  
$http.get('/my-request').success(function(){ 
    $scope.ready = true; 
}); 

這工作,因爲ng-if指令將創建元素只有表達式爲真。

+1

如果'flag'已經是true並且我想運行指令,如果我將使'flag = true'不會運行指令,因爲'flag'已經是' true' – saf

+0

使其成爲虛假然後成功() –

+0

它會生成新的HTML或顯示/隱藏最初存在的相同的HTML – saf