AngularJS在$ http响应之后运行编译指令

时间:2016-01-22 06:30:03

标签: javascript angularjs

在我的控制器的$ scope中,我有一个名为myObject的对象,该对象将由$ http.get(...)填充。

angular.module('myApp').controller('myController', ['$scope', function($scope) {

    this.myObject={};  //object to be loaded by $http.get

    //We initiate the request to load myObject.
    $http({
        url: '/myurl',
        method: 'GET'
    }).then(function(result){
           this.myObject = result.data;
    }, function(data, status){});

}]);

在HTML视图中,有许多依赖于myObject的指令,并且会返回错误,例如"无法读取属性' xxx' of null"如果在$ http.get返回响应之前运行它。

如何暂停在加载my.myObject之前运行的指令?

3 个答案:

答案 0 :(得分:3)

您可以通过使用ng-if包装来延迟指令的执行。你可以做类似下面的事情。

<强> HTML:

<div ng-if="vm.loadingComplete">
  <your-directive your-data="vm.myObject"></your-directive>
</div>

<强> JS:

angular.module('myApp').controller('myController', ['$scope', function($scope) {
    var vm = this; 

    // notice I have create variable vm and cached this
    // if not done so, you cannot use this.something inside nested functions
    // as this would mean something else there

    vm.myObject={};  //object to be loaded by $http.get
    vm.loadingComplete = false;

    //We initiate the request to load myObject.
    $http({
        url: '/myurl',
        method: 'GET'
    }).then(function(result){
       // you had a issue here before
       // this.myObject is not same as this.myObject outside this function
       vm.myObject = result.data;
       vm.loadingComplete = result;
    }, function(data, status){});
}]);

答案 1 :(得分:1)

假设您的指令是'testDir',

app.directive('testDir', function(){
 return {
            restrict: "AE",
            transclude: true,
            replace: false,
            //templateUrl: "/views/api_status_chart.html",
            scope: {
                myData: '=' // this is your data from the controller
            },
            link: function (scope, element, args) {

                  initializeDirective function(){
                       // wrap all your functionality inside this function
                  }

                  scope.$watch('myData', function(newVal){
                       // if new value is not null do your all computation
                       if(newVal != null && newVal.length > 0){
                              initializeDirective();
                       }
                  });
            }
});

<test-dir my-data="myObject "> </test-dir>

<强>概念

仅在数据不为空时才执行所有功能。否则什么都不做。

答案 2 :(得分:0)

使用角度js附带的ngIf指令,并在使用之前验证html模板中的myObject

`<div ng-if="myObject!=== null"> <!-- set myObject = null by default in controller -->
   <!-- use myObject's values to generate DOM -->
</div>`

由于angular对双向绑定起作用,每当myObject设置为一个值时,angular将在html模板上评估ng-if指令。

ngIf - directive in module ng