【问题标题】:angularjs model doesnt get updated on select changeangularjs模型不会在选择更改时更新
【发布时间】:2014-11-19 15:00:07
【问题描述】:

我正在尝试集成 angularjs 和 jquery 选择的插件,一切正常,但是当更改模型时没有更新,有人可以告诉我如何去做吗,youtube 上有一个视频解释了相同但我不可以访问 youtube,我们将不胜感激任何帮助

这是我的html代码:

<select id="categories" data-placeholder="Select Categories" 
    chosen="categories" ng-model="categoriesSelected" multiple="" 
    ng-options="category.name for category in categories"></select>
<div ng-repeat="category in categoriesSelected">{{category.name}}</div>

这是角码:

app.directive('chosen', function()
{
    return {
        restrict : 'A',
        link : function(scope, element, attr)
        {
            console.log(attr);

            $("#" + attr.id).chosen();

            scope.$watch(attr.chosen, function(oldVal, newVal)
            {
                $("#" + attr.id).trigger('chosen:updated');
            });

            scope.$watch(attr.ngModel, function()
            {
                $("#" + attr.id).trigger('chosen:updated');
            });

        }
    };
})

app.controller("workbenchController", function($scope, $http, workbenchService)
{
    $scope.categories = [];
    $scope.categoriesSelected = [];
    workbenchService.categoriesList().then(function(data)
    {
        $scope.categories = data;
    })
}

【问题讨论】:

  • 你有没有在选择输入中尝试 ng-change

标签: angularjs angularjs-directive angularjs-scope jquery-chosen


【解决方案1】:

原因可能是 jquery 插件在 Angular 应用程序编译后进行 DOM 修改,这意味着 Angular 应用程序将无法使用该元素作为应用程序的一部分(没有 ng-model、ng-show 等对于该元素),因此您必须尝试不使用 jquery 插件,而是使用角度指令,这样指令将与应用程序一起编译,并且您将让一切按预期工作。

解决您的问题的更好方法是使用 ui-select 指令,它是一个角原生选择框,可以作为 selectize、selected 或 select2、更多信息和下载 Here

和一个有效的 plunker 示例 Here

【讨论】:

    【解决方案2】:

    问题出在你的控制器上:

    app.controller("workbenchController", function($scope, $http, workbenchService)
    {
        $scope.data = {};
        $scope.data.categories = [];
        $scope.data.categoriesSelected = [];
    
        workbenchService.data.categoriesList().then(function(data)
        {
            $scope.data.categories = data;
        })
    }
    

    所以你的Html必须指向:

    <select id="categories" data-placeholder="Select Categories" 
        chosen="categories" ng-model="data.categoriesSelected" multiple="" 
        ng-options="category.name for category in categories"></select>
    <div ng-repeat="category in data.categoriesSelected">{{category.name}}</div>
    

    请阅读:Understanding scopes

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-03
      • 1970-01-01
      • 1970-01-01
      • 2015-12-14
      • 2015-11-11
      • 1970-01-01
      相关资源
      最近更新 更多