2015-06-11 42 views
0

我在我的作用域上聲明瞭一個返回對象的函數。 我嘗試將此函數的結果傳遞給自定義指令,但它會觸發無限的摘要循環(打開您的控制檯並運行代碼段)。如何將函數調用的結果傳遞給指令?

似乎objectEquality標誌沒有設置在觀察者上,這就是爲什麼角度沒有進行深度比較。

我在做什麼錯?是否有可能實現或者我是否違反了Angular原則?

var app = angular.module('plunker', []); 
 

 
app.controller('MainCtrl', function($scope) { 
 
    $scope.bar = function() { 
 
    return { 
 
     baz: 'qux' 
 
    }; 
 
    }; 
 
}).directive('myDirective', function() { 
 
    return { 
 
    restrict: 'E', 
 
    scope: { 
 
     foo: '=' 
 
    } 
 
    } 
 
});
<script src="https://code.angularjs.org/1.3.16/angular.js"></script> 
 

 
<div ng-app="plunker"> 
 
    <div ng-controller="MainCtrl"> 
 
    <my-directive foo="bar()"></my-directive> 
 
    </div> 
 
</div>

+0

爲什麼你需要這個功能? –

回答

1

嘗試使用單向結合(&)來代替。這將爲您的指令範圍附加一個getter函數,您可以使用該函數來獲取bar函數的結果。

見下文:

var app = angular.module('plunker', []); 
 

 
app.controller('MainCtrl', function($scope) { 
 
    $scope.bar = function() { 
 
    return { 
 
     baz: 'qux' 
 
    }; 
 
    }; 
 
}).directive('myDirective', function() { 
 
    return { 
 
    restrict: 'E', 
 
    scope: { 
 
     foo: '&' 
 
    }, 
 
    link: function(scope){ 
 
     console.log(scope.foo()) 
 
    } 
 
    } 
 
});
<script src="https://code.angularjs.org/1.3.16/angular.js"></script> 
 

 
<div ng-app="plunker"> 
 
    <div ng-controller="MainCtrl"> 
 
    <my-directive foo="bar()"></my-directive> 
 
    </div> 
 
</div>

+0

我永遠不會習慣它...非常感謝! – Quentin

1

當你通過函數傳遞你的範圍,你必須使用 '&'

var app = angular.module('plunker', []); 
 

 
app.controller('MainCtrl', function($scope) { 
 
    $scope.bar = function() { 
 
    return { 
 
     baz: 'qux' 
 
    }; 
 
    }; 
 
}).directive('myDirective', function() { 
 
    return { 
 
    restrict: 'E', 
 
    scope: { 
 
     foo: '&' 
 
    } 
 
    } 
 
});
<script src="https://code.angularjs.org/1.3.16/angular.js"></script> 
 

 
<div ng-app="plunker"> 
 
    <div ng-controller="MainCtrl"> 
 
    <my-directive foo="bar()"></my-directive> 
 
    </div> 
 
</div>

相關問題