在 Angularjs 中将数据从视图传递到控制器

Passing data from View to Controller in Angularjs

我在控制器中从 URL 获取数据,但我需要它是动态的

d3.json("http://localhost:2016/get_stats_for?brand_name="+$scope.brand,function(data))

我想从视图中的文本框中获取 $scope.brand

我该怎么做?

编辑 2 或者,您可以改用 ng-change

app.controller('MyController', function($scope, MyService){
   $scope.brand = 'D&G'; //initialize value
   $scope.onBrandChange = function(){
       MyService.getByBrand($scope.brand).then(function(res){
           var result = res.data; //here is your JSON
       });
   });
});

app.service('MyService', function($http){
    this.getByBrand = function(brand){
        var URL = "http://localhost:2016/get_stats_forbrand_name="+brand;
        return $http.get(URL);
    };
});
<div ng-controller='MyController'>
<input type='text' ng-change='onBrandChange()' ng-model-options="{debounce: 100}" ng-model='brand'></input>
</div>


您想跟踪作用域中变量的变化吗?

$scope.$watch('brand', function(newValue, oldValue){
   //fetch the json file
});

将以下内容添加到视图上的 ng-model 元素中

ng-model-options="{debounce: 100}"

仅当元素未更改的时间超过 100 毫秒时才会发生更新(因此在快速输入的情况下,浏览器不会被多个获取请求限制)