簡體   English   中英

如何監視指令中的$ scope變化?

[英]How to watch for $scope changes in a directive?

我有一個這樣的指令:

app.directive('selectedForm', function(MainService) {
    return {
        scope: {
            formName: '=currentForm'
        },
        restrict: 'E', 
        link: function($scope, iElm, iAttrs, controller) {
            $scope.$watch('formName', function(oldV, newV) {
                console.log(iElm);
                if (someCondition) {
                    MainService.getForm($scope.formName).then(function(re) {
                        iElm.html(re);
                    });
                }
            });
        }
    };
});

但是,問題是我無法監視更改。 我在DOM中有一個<select>元素,它會更改currentForm ngModel的值。 但是,即使我選擇了一個選項, watch功能也無法正常工作。 我想念什么嗎?

您不能以與在angular controller相同的方式在angular directive中使用相同的$watch 相反,將其更改為如下所示:

將您的html select元素更改為以下內容:

<select model="selectedElements">
    ...
    ...
</select>

然后在您的指令中,將$watch更改為:

...
link: function($scope, iElm, iAttrs, controller) {
            $scope.$watch('iAttrs.model', function(oldV, newV) {
...

另請參閱: 可以在自定義指令中監視范圍嗎?


編輯:

在您的案例中,用於監視<select ng-model='currentForm'> ... </select>值的代碼為:

...
link: function($scope, iElm, iAttrs, controller) {
            $scope.$watch('iAttrs.currentForm', function(oldV, newV) {
...

編輯2

根據評論更新:

在你的HTML

<selected-form ng-model="currentForm"></selectedForm>

並在您的控制器中

...
link: function($scope, iElm, iAttrs, controller) {
            $scope.$watch('iAttrs.ngModel', function(oldV, newV) {
...

編輯3

查看此更新的插件:

https://plnkr.co/edit/v5EnmpQ9UtApnM5ErnYi?p=preview

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM