Angular UI Bootstrap and Angular Color Picker return undefined for ng-model

10,385

Solution 1

I know this was asked a while ago.. but for the benefit of anyone else seeing this page.

When an angular binding (such as ng-model) is retrieving a value it will travel up the scope hierarchy until it finds it.. however when setting a value it wont travel up the hierarchy. This is because it is based on how javascript prototype inheritance works.

If you follow this logic then if you bound to a property of an object the binding would then need to travel up the hierarchy to fetch that object and then set a value on it.. therefore as per the updated jsbin note that on the parent controller i am initialising an object on the scope. $scope.colors = {}; and then binding to properties on that object.

<input colorpicker="rgba" type="text" ng-model="colors.back1Color" />
<input colorpicker="rgba" type="text" ng-model="colors.backColor" />

As a rule, Miško Hevery said if your ng-model doesn't have a dot '.' you are probably doing it wrong.

Drammys answer may also work (because he is essentially binding to the 'vm' object, but this is a different style for controllers, along with 'Controller As' syntax and is optional)

Solution 2

I got it working by defining the controller as vm and populating the vm object in the controller...

<body ng-controller="mainCtrl as vm">Normal
  <input colorpicker="rgba" type="text" ng-model="vm.back1Color" /><hr/>
  <tabset><tab heading="In Tab">
    <input colorpicker="rgba" type="text" ng-model="vm.backColor" />
  </tab></tabset>

var app = angular.module('app',['colorpicker.module','ui.bootstrap']);
app.controller('mainCtrl',function($scope){
  var vm = this;
  vm.backColor = '';
  vm.back1Color = '';

  $scope.change = function(){
    alert(vm.backColor);
  };
  $scope.change1 = function(){
     alert(vm.back1Color);
  };
});

Personally I prefer to define all the controller properties I wish to expose to the view on this "vm" object in the controller and then declare the controller as vm in the view and bind to the vm object's properties. It feels neater and better defined to me.

Updated the jsbin here.

Share:
10,385
MBehtemam
Author by

MBehtemam

Mohammad Bagher Ehtemam (MBehtemam) =&gt; MB Coding Loving MEMEX

Updated on June 04, 2022

Comments

  • MBehtemam
    MBehtemam almost 2 years

    In my application i need a color picker with alpha transparency and after searching finally find angular-bootstrap-colorpicker so i try to use this.when normally i use this plugin it work and ng-model correctly but when i use this directive in angular-ui bootstrap , the plugin doesn't work and return undefined. for this problem i create a jsbin with tabed mode and normal bod . i have same problem with other directives of angular-ui bootstrap like modal