angular: watch for filtered value in directive

吃可爱长大的小学妹 提交于 2019-12-12 01:36:46

问题


I'm trying to implement a directive that draws a chart based on given values. I want the pass the data for the plot from the template. I have a working solution, passing the data in ng-model, for which I can then add a $scope.watch statement. But that doesn't work with filtered data, and I don't need two-way binding.

Ideally, the html should look like:

 <chart ???????="list | filter" />

The directive, I guess, should look like:

  return{
    restrict: 'C',
    link: function(scope, elem, attrs){
        var chart = null

        scope.$watch(????, function(v){
             if(!chart){
                chart = $.plot(elem, v , options);
                elem.show();
            }else{
                chart.setData(v);
                chart.setupGrid(); 
                chart.draw();
            }
        });
    }
};

Is there an angular way to achieve this?


回答1:


What about saving the filtered list in a different variable in your controller? something like:

$scope.filteredList = $filter('yourFilter')($scope.list);

and in the HTML:

<chart ????="filteredList" />

You only need to make sure you update filteredList whenever list changes.




回答2:


What about actually placing binding on the ???? variable:

<chart ???????="{{list | filter}}" />

You might also want to add in your directive:

  return{
    restrict: 'C',
    scope: {
        ????: "@",
    },
    link: function(scope, elem, attrs){
        var chart = null

        scope.$watch(????, function(v){
             if(!chart){
                chart = $.plot(elem, v , options);
                elem.show();
            }else{
                chart.setData(v);
                chart.setupGrid(); 
                chart.draw();
            }
        });
    }
};


来源:https://stackoverflow.com/questions/24352802/angular-watch-for-filtered-value-in-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!