2016-08-15 3 views
1

Я сделал это раньше. Он всегда работает. По какой-то причине он больше не работает.Угловое простое связывание не работает в контроллере

У меня есть следующие два входа ..

<input id="input1" ng-model="searchString2" /> 

<input ng-model="searchString2" ng-keypress="($event.which === 13)?searchPatient():0" type="text" class="form-control" placeholder=""> 

В мой контроллер:

$scope.searchString2 = "test"; 

$scope.searchPatient = function() { 
      $scope.response = null; 
      alert($scope.searchString2); 

      var url = baseUrl + 'api/patient?etag=' + $scope.etag.value + '&searchString=' + $scope.searchString2; 

      $http({ 
       method: 'GET', 
       url: url 

      }).then(function successCallback(response) { 

       $scope.response = response.data; 


      }, function errorCallback(response) { 
       $scope.errorMessage = response.statusText; 
      }); 
     }; 

Когда я печатаю в любой из двух входов, другой вход обновляется, как ожидалось. Однако я вызываю функцию searchPatient, значение $ scope.searchString2 всегда равно ее начальному значению ("test").

Любая идея, почему?

UPDATE

Это, как я установить контроллер:

angular 
    .module('myApp', 
    [ 
     'ngRoute', 
     'myApp.ctrl.home', 
     'myApp.ctrl.etag', 
     'myApp.ctrl.about', 
     'myApp.ctrl.partner' 
    ]) 
    .config([ 
     '$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) { 

      var baseUrl = $("base").first().attr("href"); 
      //console.log("base url for relative links = " + baseUrl); 

      // Specify the three simple routes ('/', '/About', and '/Contact') 
      $routeProvider.when('/', 
      { 
       templateUrl: baseUrl + '/Home/Home', 
       controller: 'partnerCtrl', 
       activetab: 'home' 
      }); 
      $routeProvider.when('/Priorx', 
      { 
       templateUrl: baseUrl + '/Home/About', 
       controller: 'aboutCtrl', 
       activetab: 'priorx' 
      }); 

      $routeProvider.otherwise({ 
       redirectTo: '/' 
      }); 

      // Specify HTML5 mode (using the History APIs) or HashBang syntax. 
      $locationProvider.html5Mode(false).hashPrefix('!'); 

     } 

CONTROLLER

angular 
    .module("myApp.ctrl.about", ["ngCookies"]) 
    .controller("aboutCtrl", ["$scope", "$sce", "$http", "$window", "$cookies", function ($scope, $sce, $http, $window, $cookies) { 

     var w = angular.element($window); 
     var iframe = angular.element(document.querySelector('#iFrame')); 

     $scope.version = "1.0.0"; 
     $scope.windowWidth = 0; 
     $scope.windowHeight = 0; 

     var setDimensions = function() { 
      $scope.windowWidth = w.width(); 
      $scope.windowHeight = w.height(); 
     }; 

     w.bind('resize', function() { 
      $scope.$apply(function() { 
       setDimensions(); 
      }); 
     }); 
     setDimensions(); 

     var baseUrl = $("base").first().attr("href"), 
      _login = function (username, password) { 
       //$http.post(baseUrl + 'api/login', { 'username': username, 'password': password }) 
       // .success(function (data, status, headers, config) { 
       //  if (data === "") 
       //   $scope.errorMessage = "Login failed."; 
       //  else { 
       //   $scope.etag = { 
       //    value: data, 
       //    expiration: new Date(new Date().getTime() + 8 * 60 * 60 * 1000) 
       //   }; 
       //   setEtag($scope.etag); 
       //  } 

       // }) 
       // .error(function (data, status, headers, config) { 

       //  if (data.exceptionMessage) 
       //   $scope.errorMessage = data.exceptionMessage; 
       //  else { 
       //   $scope.errorMessage = "An error has occured!"; 
       //  } 
       // }); 



       $http({ 
        method: "POST", 
        url: baseUrl + 'api/login', 
        data: { username: username, password: password } 
       }).then(function successCallback(response) { 
        var data = response.data; 
        if (data === "") 
         $scope.errorMessage = "Login failed!"; 
        else { 
         $scope.etag = { 
          value: data, 
          expiration: new Date(new Date().getTime() + 8 * 60 * 60 * 1000) 
         }; 
         setEtag($scope.etag); 
        } 
       }, function errorCallback(response) { 
        $scope.errorMessage = response.statusText; 
       }); 

      }, 

      _logoff = function (etag) { 
       $http.post(baseUrl + 'api/logout', 
         "=" + etag, 
         { 
          headers: { 
           'Content-Type': 'application/x-www-form-urlencoded' 
          } 
         }) 
        .success(function (data, status, headers, config) { 
         if (data === true) { 
          clearEtag(); 
         } else { 
          $scope.errorMessage = "failed to logoff"; 
         } 
        }) 
        .error(function (data, status, headers, config) { 
         console.log(data); 
         if (data.exceptionMessage) 
          $scope.errorMessage = data.exceptionMessage; 
         else { 
          $scope.errorMessage = "An error has occured!"; 
         } 
        }); 
      }, 

      setEtag = function (etag) { 
       console.log('etag', etag); 
       $cookies.putObject('etag', etag); 
      }, 

      clearEtag = function() { 
       $cookies.remove('etag'); 
       $scope.etag = null; 
      }, 

      getEtag = function() { 
       var e = $cookies.getObject('etag'); 


       if (e && e.value && e.value.length > 0) { 

        if (new Date() < new Date(e.expiration)) 
         $scope.etag = e; 
        else { 
         $scope.warningMessage = "Cached ETAG was removed because it has expired!"; 
         clearEtag(); 
        } 
       } else $scope.etag = null; 
      }; 

     $scope.errorMessage = ""; 
     $scope.warningMessage = ""; 
     $scope.username = "PJT"; 
     $scope.password = "benoit"; 
     $scope.etag = null; 
     $scope.loading = false; 
     $scope.infoMessagePatient = ""; 
     $scope.errorMessagePatient = ""; 
     $scope.patient = {}; 
     $scope.response = null; 
     $scope.searchString2 = ""; 
     $scope.appUrl = "http://noranda.pfsserver.com/inr/index.html?lang=fr#/"; 
     $scope.srciFrame = $sce.trustAsResourceUrl($scope.appUrl); 
     $scope.url = $scope.appUrl; 

     // functions 


     $scope.connect = function() { 
      $scope.errorMessage = ""; 
      _login($scope.username, $scope.password); 
     }; 

     $scope.logout = function() { 
      $scope.errorMessage = ""; 
      _logoff($scope.etag.value); 
     }; 


     $scope.randomPatientData = function() { 

      $http({ 
       method: 'GET', 
       url: 'https://randomuser.me/api?nat=ca' 
      }) 
       .then(function successCallback(response) { 
        console.log(response); 
        var random = response.data.results[0]; 

        $scope.patient.ln = random.name.last; 
        $scope.patient.fn = random.name.first; 
        $scope.patient.bdate = new Date(random.dob); 
        $scope.patient.adr = random.location.street; 
        $scope.patient.city = random.location.city; 
        $scope.patient.postalCode = random.location.postcode; 
        $scope.patient.provState = random.location.state; 
        $scope.patient.country = random.nat; 

        $scope.patient.telHome = random.phone; 
        $scope.patient.telOff = random.phone; 
        $scope.patient.telCel = random.cell; 

        $scope.patient.sex = random.gender === "male" ? "M" : "F"; 
        $scope.lang = "FRANCAIS"; 
        $scope.email = random.email; 

       }, 
        function errorCallback(response) { 
         $scope.errorMessage = response.statusText; 
        }); 

     }; 

     $scope.createPatient = function() { 
      $scope.infoMessagePatient = ""; 
      $scope.errorMessagePatient = ""; 

      $scope.patient.etag = $scope.etag.value; 

      $http({ 
       method: 'POST', 
       url: baseUrl + 'api/patient', 
       data: $scope.patient 
      }).then(function successCallback(response) { 

       if (response.data.Success === true) 
        $scope.infoMessagePatient = "Patient Created"; 
       else if (response.data.Success === false) { 
        $scope.errorMessagePatient = response.data.Message; 
        alert(response.data.Message); 
       } 

      }, function errorCallback(response) { 
       $scope.errorMessagePatient = response.statusText; 
      }); 
     }; 


     $scope.searchPatient = function (s) { 
      $scope.response = null; 


      var url = baseUrl + 'api/patient?etag=' + $scope.etag.value + '&searchString=' + s; 

      $http({ 
       method: 'GET', 
       url: url 

      }).then(function successCallback(response) { 

       $scope.response = response.data; 


      }, function errorCallback(response) { 
       $scope.errorMessage = response.statusText; 
      }); 
     }; 

     $scope.test = function() { 
      console.log($scope.searchString2); 
     }; 

     $scope.goto = function(path) { 
      var url = $scope.appUrl.replace("#", "&et=" + $scope.etag.value + "#"); 
      $scope.url = url + path; 
      $scope.srciFrame = $sce.trustAsResourceUrl($scope.url); 
     }; 

     //$scope.gotoRaw = function (url) { 
     // $scope.url = url; 
     // $scope.srciFrame = $sce.trustAsResourceUrl(url); 
     //}; 

     $scope.gotoPatient = function(id, type) { 
      $scope.gotoUrl({ 
       etag: $scope.etag.value, 
       urlType: type, 
       custId: id 
      }); 
     }; 

     $scope.gotoPage = function(type) { 
      $scope.gotoUrl({ 
       etag: $scope.etag.value, 
       urlType: type, 
       //lang: "en" 
      }); 
     }; 

     $scope.gotoUrl = function(data) { 
      $http({ 
       method: 'POST', 
       url: baseUrl + 'api/url', 
       data: data 
      }).then(function successCallback(response) { 

       $scope.url = response.data.Data; 
       $scope.srciFrame = $sce.trustAsResourceUrl(response.data.Data); 


      }, function errorCallback(response) { 
       $scope.errorMessage = response.statusText; 
      }); 
     } 

     getEtag(); 
    }]); 
+0

Мне нужно было бы больше кода от вашего контроллера, но почему бы не отправить значение непосредственно вашей функции? '' '($ event.which === 13)? searchPatient (searchString2): 0''' –

+1

Похоже, что знаменитая' ng-model' нуждается в точечной проблеме: http://stackoverflow.com/questions/18128323/if-you-are-not-use-a-dot-in-your-angularjs-models-you-are-doing-it-wrong –

+0

Как добавить контроллер в элемент html? –

ответ

0

я создал скрипку из вашего кода, но я Жду» t сталкиваются с какой-либо ошибкой. Вы уверены, что правильно привязали свой контроллер и приложение к своему HTML? Вот код;

В HTML;

<div ng-app=myApp> 
    <div ng-controller=myController> 

<input id="input1" ng-model="searchString1" /> 

<input ng-model="searchString2" ng-keypress="($event.which === 13)?searchPatient():0" type="text" class="form-control" placeholder=""> 
<p> 
SearchString1 : {{searchString1}} 
</p> 
SearchString2 : {{searchString2}} 

В JS;

'use strict'; 

var myApp = angular.module('myApp',[]); 

myApp.controller('myController', ['$scope', function($scope) { 
$scope.searchString1 = ""; 
$scope.searchString2 = ""; 

$scope.searchPatient = function() { 
      $scope.response = null; 
      alert($scope.searchString2); 

      var url = baseUrl + 'api/patient?etag=' + $scope.etag.value + '&searchString=' + $scope.searchString2; 

      $http({ 
       method: 'GET', 
       url: url 

      }).then(function successCallback(response) { 

       $scope.response = response.data; 


      }, function errorCallback(response) { 
       $scope.errorMessage = response.statusText; 
      }); 
     }; 
}]); 

Рабочий URL скрипта; https://jsfiddle.net/z5y03kuk/1/

Смежные вопросы