2016-10-22 1 views
1

Как вы можете запустить событие ng-click? Я пробовал все, чтобы заставить это работать. Я знаю, что предупреждение работает изначально, но после отображения списка, вполне волшебным образом все кнопки не могут функционировать.ng-click не запускается в или из ng-таблицы

Отображение этой страницы (предварительное предупреждение). Я проверял, что каждая кнопка для получения подробной информации получает уникальный идентификатор. Как вы можете видеть, я также попробовал $ parent (так как некоторые из кнопок находятся внутри ng-repeat), а также $ ccccccp4, чтобы попытаться заставить вещи выполнить (т. Е. Кнопки с деталями). Это почти как если бы, после того, как первоначально отображения, страница потеряла ссылку на angularjs файл, поскольку ничто функции:

When page is first displayed

After getting the data

Вот файл AngularJS:

var app = angular.module("EmployeeApplication", []) 
.controller("EmployeeController", 
    function ($scope, $http,$window) { 

     AngularInit(); 

     function AngularInit() { 
      //This will be called once per form load, via the ng-load function on the div 
      $scope.name = ''; 
      $scope.gender = ''; 
      $scope.salary = ''; 
      $scope.id = ''; 
      $scope.DisplayAction = 'Unknown'; 
      $scope.gotdata = false; 
      DisplayList(); 
      ShowAlert('test') 
     } 

     function GetAllEmployees($http) { 
      //$scope.Message = 'NULL'; 
      //$scope.employees = {}; 
      $http.get('http://localhost:65315/api/employee').then(function (response) { 
       $scope.employees = response.data; 
       $scope.Message = 'OK'; 
       $scope.gotdata = true; 
      }, 
      function (err) { 
       $scope.Message = 'Call failed' + err.status + ' ' + err.statusText; 
       $scope.employees = {}; 
       $scope.gotdata = false; 
      } 
      ); 

      //window.setTimeout(function() { 
      // $scope.gotdata = true; 
      //}, 1000); 
     }; 

     function DisplayList() { 
      //call the web service to get the list of people 
      //set the display action so that the list will be displayed 
      GetAllEmployees($http) 
      $scope.DisplayAction = 'List'; 
     }; 

     function CreateNewEmployee() { 
      $scope.name = ''; 
      $scope.gender = ''; 
      $scope.salary = ''; 
      $scope.id = ''; 
      $scope.DisplayAction = 'Create'; 
      $scope.$apply(); 
     }; 

     function ShowDetails(id) { 
      //call the web service to get the details of the person 
      ShowAlert('test') 
      $scope.gotdata = false; 
      $http.get('http://localhost:65315/api/employee/' + id).then(function (response) { 
       $scope.employees = response.data; 
       $scope.DisplayAction = 'Details'; 
       $scope.Message = 'OK'; 
      }, 
      function (err) { 
       $scope.Message = 'Call failed' + err.status + ' ' + err.statusText; 
       $scope.employees = {}; 
      } 
      ); 


      //Set the $scope.CurrentEmployee 
      $scope.$apply(); 
     }; 
     function ShowAlert(msg) 
     { 
      $window.alert(msg); 
     } 

     function CreateEmployee() { 

      //perform the actual creation based on $scope.CurrentEmployee 

      //if successful 
      DisplayList(); 
     }; 

     function DeleteEmployee(id) { 
      $scope.DisplayAction = 'Delete'; 
      $scope.$apply(); 
     }; 

     function DoDeleteEmployee(id) { 
      //Perform actual deletion 
      //if successful 
      DisplayList(); 
     }; 

     function EditEmployee(id) { 
      //get the employee based on ID 
      $scope.DisplayAction = 'Edit'; 
      $scope.$apply(); 
     }; 

     function EditUpdate() { 
      //perform the actual update based on $scope.id 

      //if successful 
      DisplayList(); 
     }; 
    } 

); 

//angular.module('EmployeeApplication', []) 
// .controller('EmployeeController', ['$scope', '$window', function ($scope, $window) { 
//  $scope.greeting = 'Hello, World!'; 
//  $scope.doGreeting = function (greeting) { 
//   $window.alert(greeting); 
//  }; 
// }]); 



var app = angular.module("MyModule", []).controller("MyController", function ($scope, $http) 
{ 
    $scope.MadeItHereMessage = 'We made it to the controller (first controller)'; 
    $scope.employees = {}; 
    $http.get('http://localhost:65315/api/employee').then(function (response) { 
     $scope.employees = response.data; 
     $scope.Message = "OK"; 
    }, 
    function (err) 
    { 
     $scope.Message = "Call failed" + err.status + " " + err.statusText; 
    } 
    ); 

}); 


//var app = angular.module("MyModule", []).controller("MyController", function initController($scope) 
//{ 
//  $scope.MadeItHereMessage = 'This is a loadtest'; 
//}); 

//var app = angular.module("EmployeeApplication", ['$rootscope','$scope','$http']) 
//.controller("EmployeeController", 

// function AppCtrl($rootscope,$scope, $http) 
// { 
//  $scope.DisplayAction = "List"; 
// } 

//); 

//var app = angular.module("MyModule", []).controller("MyController", function ($scope, $http) { 
// $http.get('EmployeeWebService.asmx/GetAllEmployees').then(function (response) { 
//  $scope.employees = response.data; 
// } 
// ); 

//}); 

Вот файл HTML:

<!DOCTYPE html> 
<html> 
<head> 
    <title></title> 
    <script src="Scripts/angular.js"></script> 
    <script src="Scripts/EmployeeAngular.js"></script> 
    <meta charset="utf-8" /> 
</head> 
<body ng-app="EmployeeApplication"> 

<div ng-controller="EmployeeController" ng-init="AngularInit()"> 
    {{Message}} 
    <br/> 
     {{DisplayAction}} 
    <button id="btnCreateNew1" ng-click="$parent.ShowAlert('Parent scope button pressed')">Show message from parent scope</button> 
    <br /> 
     <!--The following is for listing the entire list of employees--> 
     <div id="listSection" ng-show="DisplayAction=='List'"> 
      <!--The employees data is: {{employees}}--> 
    <!--<div id="listSection">--> 
     <table> 
      <thead>List of defined Employees</thead> 
      <tr> 
       <!--<td><button id="btnCreateNew" ng-click="CreateNewEmployee()">Create Employee</button></td>--> 
       <td><button id="btnCreateNew" ng-click="$rootscope.ShowAlert('Create button pressed')">Create Employee</button></td> 
      </tr> 
      <tr> 
       <td ng-show="gotdata"> 

        <table id="EmployeeList"> 
         <thead> 
          <tr> 
           <th>ID</th> 
           <th>Name</th> 
           <th>Gender</th> 
           <th>Salary</th> 
          </tr> 
         </thead> 
         <tbody> 
          <tr ng-repeat="employee in employees" ng-if="employees && employees!={undefined}"> 
           <td>{{employee.id}}</td> 
           <td>{{employee.name}}</td> 
           <td>{{employee.gender}}</td> 
           <td>{{employee.salary}}</td> 

           <td><button id="btnDetailsA{{employee.id}}" ng-click="$parent.ShowDetails({{employee.id}})">Details</button></td> 
           <td><button id="btnDetailsB{{employee.id}}" ng-click="$parent.ShowDetails({{employee.id}})">Details B</button></td> 
           <td><button id="btnDetailsC{{employee.id}}" ng-click="ShowDetails({{employee.id}})">Details C</button></td> 
           <td><button id="btnDetailsD{{employee.id}}" ng-click="$scope.ShowDetails({{employee.id}})">Details D</button></td> 
           <td><button id="btnDetailsE{{employee.id}}" ng-click="$rootscope.ShowDetails({{employee.id}})">Details E</button></td> 

           <td><button id="btnDelete{{employee.id}}" ng-click="$parent.DeleteEmployee({{employee.id}})">Delete</button></td> 
           <td><button id="btnEdit{{employee.id}}" ng-click="$parent.EditEmployee({{employee.id}})">Edit</button></td> 
          </tr> 
         </tbody> 
        </table> 
       </td> 
      </tr> 
     </table> 
    </div> 
     <!--The following is for listing the details of a single employee--> 
     <div id="DetailsSection" ng-show="DisplayAction=='Details'"> 
      <table> 
       <tr> 
        <td>ID:</td> 
        <td> <input id="DetailsID" value={{employee.id}} /></td> 
       </tr> 
       <tr> 
        <td>Name:</td> 
        <td><input id="DetailsName" value={{employee.name}} /> </td> 
       </tr> 
       <tr> 
        <td>Gender:</td> 
        <td><input id="DetailsGender" value={{employee.gender}} /> </td> 
       </tr> 
       <tr> 
        <td>Salary:</td> 
        <td><input id="DetailsSalary" value={{employee.salary}} /> </td> 
       </tr> 
       <tr> 
        <td> 
         <button id="NavTolist" ng-click="DisplayList()">Back to List</button> 
        </td> 
        <td> 
         <button id="NavToDelete" ng-click="DeleteEmployee({{id}})">Delete</button> 
        </td> 
        <td> 
         <button id="NavToEdit" ng-click="EditEmployee({{id}})">Edit</button> 
        </td> 
       </tr> 
      </table> 
     </div> 
     <!--The following is for editing a employee--> 
     <!--<div id="EditSection" ng-show="DisplayAction=='Edit'"> 
      <table> 
       <tr> 
        <td>ID:</td> 
        <td> 
         <input id="ID" value={{id}} /> 
        </td> 
       </tr> 
       <tr> 
        <td>Name:</td> 
        <td><input id="" value={{name}} ng-bind="name" /> </td> 
       </tr> 
       <tr> 
        <td>Gender:</td> 
        <td><input id="" value={{gender}} ng-bind="gender" /> </td> 
       </tr> 
       <tr> 
        <td>Salary:</td> 
        <td><input id="" value={{salary}} ng-bind="salary" /> </td> 
       </tr> 
       <tr> 
        <td> 
         <button id="EditUpdate" type="button" value="Update" ng-click="EditUpdate()"></button> 
        </td> 
        <td> 
         <button id="NavTolistEdit" type="button" value="Back to List" ng-click="DisplayList()"></button> 
        </td> 
        <td> 
         <button id="NavToDeleteEdit" type="button" value="Delete" ng-click="DeleteEmployee({{id}})"></button> 
        </td> 
       </tr> 
      </table> 
     </div>--> 
     <!--The following is for verification of deletion--> 
     <div id="DeletionSection" ng-show="DisplayAction=='Delete'"> 
      <table> 
       <tr> 
        <td>Do you really want to delete {{name}}</td> 
        <td></td> 
        <td> 
         <button id="btnCancelDelete" type="button" value="No" ng-click="DisplayList()"></button> 
        </td> 
        <td> 
         <button id="btnDeleteEmployee" type="button" value="Yes" ng-click="DoDeleteEmployee({{id}})"></button> 
        </td> 
       </tr> 
      </table> 
     </div> 
     <!--The following is for creation of a employee--> 
     <!--<div id="CreationSection" ng-show="DisplayAction=='Create'"> 

      <table> 
       <tr> 
        <td>Name:</td> 
        <td><input id="" value="" ng-bind="name" /> </td> 
       </tr> 
       <tr> 
        <td>Gender:</td> 
        <td><input id="" value="" ng-bind="gender" /> </td> 
       </tr> 
       <tr> 
        <td>Salary:</td> 
        <td><input id="" value="" ng-bind="salary" /> </td> 
       </tr> 
       <tr> 
        <td> 
         <button id="btnCreateEmployee" type="button" value="Delete" ng-click="CreateEmployee()"></button> 
        </td> 
        <td> 
         <button id="NavTolistEdit" type="button" value="Back to List" ng-click="DisplayList()"></button> 
        </td> 
       </tr> 
      </table> 

     </div>--> 
    </div> 
</body> 
</html> 
+0

Почему вы сохраняете функции javascript? вы должны иметь либо контроллер, либо ('this.'), либо функции области видимости (' $ scope.'). Кроме того, вы можете сыграть с скрипкой или plnkr? – tanmay

ответ

0

в отличие от обработчиков ваниль событий, нг-клик будет искать обработчик событий в области контроллера, поэтому если у вас есть:

<button id="NavTolist" ng-click="DisplayList()">Back to List</button> 

контроллер должен иметь:

$scope.DisplayList = function() { 
    //call the web service to get the list of people 
    //set the display action so that the list will be displayed 
    GetAllEmployees($http) 
    $scope.DisplayAction = 'List'; 
}; 

вы могли бы заинтересованы в том, чтобы взглянуть на несколько проектов sample через Интернет, чтобы лучше организовать ваш код.

на боковой ноте, по возможности образец вашего кода, способного работать в сети, на plunker/jsfiddle/codepen, так как он предоставляет огромную помощь всем, кто хочет помочь.

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