2014-05-10 13 views
1

有時,我最終得到一個布爾表達式,以便在控制器(做一個重定向或屬於控制器的其他某種魔法)中變爲true。

(打字稿)

$scope.$watch('aComplexBoolean && expressionWith && lotsAstuff', (newValue) => { 
    if (newValue) { 
     // do my stuff, e.g. redirect etc.. 
    } 
}); 

我在想,有沒有可能在AngularJS這個速記,我真的想擺脫多餘的雜亂,且只需要調用例如$when('expr',() => { /* do stuff */ })或別的東西,同樣好,重要。

回答

2

不,沒有這樣的簡寫,如$rootScope documentation所示。但是你可以通過修改$rootScope對象自己創建它:

var myApp = angular.module('MyApp', []); 

myApp.run([ 
    '$rootScope', 
    function ($rootScope) 
    { 
     $rootScope.$watchTrue = function (expression, callback) 
     { 
      // Here, `this` refers to the scope which called the function 
      return this.$watch(
       expression, 
       function (newValue, oldValue) 
       { 
        if (newValue) {     
         callback(newValue, oldValue); 
        } 
       } 
      ); 
     }; 
    } 
]); 
2

不可以,但我更喜歡使用的提前退出,而不是包裹在一個如果:

$scope.$watch('aComplexBoolean && expressionWith && lotsAstuff', (newValue) => { 
    if (!newValue) return; 

    // do my stuff, e.g. redirect etc.. 
}); 

它也並不少見有多個早期退出,並且這種模式比包裝在if中要好得多。

+1

同意,絕對馬丁/乾淨的代碼的東西,我很早就退出我的自我(代碼遊行較少的權利) – psp