2017-12-18 55 views
0

在下面的代碼中,我有一個指令,每次輸入字段x被更改時計算變量y。變量y已公開,因此可用於聲明控制器/指令。這工作正常,但它是一個簡單的抽象,在我真實的情況下,y的計算是非常昂貴的,所以我不能計算y每次x更改。理想情況下,只有在聲明控制器/指令需要時纔會計算y。有沒有辦法實現這一點?從指令返回變量而不是暴露示波器

var app = angular.module('app', []); 
app.controller('ctl', function() { 

}); 

app.directive("theDirective", function() { 
     return { 
     restrict: "AE", 
     scope: { 
      y: '=' 
     }, 
     template: '<input ng-model="x" ng-change="xChanged()" />', 
     link: function (scope, element, attrs) { 

      scope.xChanged = function() { 
       scope.y = scope.x * 2; 
      }; 

     } 
    } 
}); 

回答

1

如果從該指令的孩子需要這樣的數據,你可以在你的指令控制器暴露的方法,然後露出孩子指令可能要求的方法做到這一點。

app.directive("theDirective", function() { 
    return { 
    restrict: "AE", 
    scope: { 
     y: '=' 
    }, 
    template: '<input ng-model="x" ng-change="xChanged()" />', 
    controller: function (scope) { 

     scope.getY = function() { 
      return scope.x * 2; 
     }; 

    } 
} 
}); 

然後你的孩子可以要求父母可以調用該方法。

app.directive("theDirectiveChild", function() { 
    return { 
    restrict: "A", 
    require: ["^theDirective"], 
    link: function(scope, element, attrs, ctrls){ 

     var theDirective = ctrls[0]; 

     var y = theDirective.getY(); 

    } 
} 
}); 

編輯:反其道而行之,在您想要的家長告訴孩子進行更新,你可以利用$ scope.broadcast()這可以觸發一個消息下來作用域鏈,它會看起來像這個。

app.directive("theDirective", function() { 
    return { 
    restrict: "AE", 
    scope: { 
     y: '=' 
    }, 
    template: '<input ng-model="x" ng-change="xChanged()" />', 
    link: function (scope) { 

     scope.on('update-the-directive' , function() { 
      scope.y = scope.x * 2; 
     }); 

    } 
} 
}); 

然後你的孩子可以要求父母可以調用該方法。

app.directive("theDirectiveParent", function() { 
    return { 
    restrict: "A", 
    link: function(scope, element){ 

     scope.click = function() { 
     scope.$broadcast('update-the-directive'); 
     } 

    } 
} 
}); 
+0

謝謝,但我需要的功能的指令,以從父叫,而不是從編輯我的答案,包括場景,以及一個孩子 – ps0604

+0

。 –

+0

這種方法存在問題。由於'$ broadcast'是異步的,如果子進程中的函數需要時間來處理,則父進程不知道何時結束,因此它不能從該作用域中獲取該變量。 – ps0604