angularjsangular-ui-bootstrapangular-ui

Variable in Angular Modal UI not watched


In this plunk I have an Angular Modal UI with a variable that is watched, however the watch function is not triggered when the variable is changed, what's wrong?

Javascript

var app = angular.module('app', ['ui.bootstrap']);
app.controller('ctl', function ($scope,$uibModal) {

        $scope.x = 'a';

        $scope.open = function(){
          $scope.modalInstance = $uibModal.open({
              templateUrl: 'myModalContent.html',
              scope: $scope
            }); 
        };

        $scope.close = function(){
          $scope.modalInstance.close();
        };


        $scope.$watch('x', function (newValue, oldValue) {
          if (typeof newValue === 'undefined')
              return;
           alert('value='+$scope.newValue);
       });
});

HTML

<button ng-click="open()">Open</button>
<script type="text/ng-template" id="myModalContent.html">
   <div class="modal-header">
      <h4 class="modal-title">The Title</h4>
      value <input type="text" ng-model="x" />
      <button ng-click="close()">Close</button>
   </div>
</script>

Solution

  • Just tested in the plunker, $uibModal needs your controller in order to bind to your scope.

    Change;

    $scope.open = function(){
          $scope.modalInstance = $uibModal.open({
              templateUrl: 'myModalContent.html',
              scope: $scope
            }); 
        };
    

    To;

    $scope.open = function(){
          $scope.modalInstance = $uibModal.open({
              templateUrl: 'myModalContent.html',
              scope: $scope,
              controller: "ctl"
            }); 
        };
    

    If you are using a .js file for it, you'd use controllerUrl = "path/to/jsfile.js" plus the name of said controller.