简体   繁体   中英

ng-click function is not called with onclick in a AngularJS?

I have to call the ng-click function with the onClick but in my case ng-click function is not

 //Controller function $scope.editProductDetail = function(productObject) { $scope.getProduct = productObject; } 
 <a href="#" onclick="document.getElementById('editProduct').style.display='block'" ng-click="editProductDetail(list)" target="_self"> </a> 

call but model is open with onClick function?

It seems you're trying to set a class to the selected item from a product list, it seems you're confusing some AngularJS concepts.

  1. If you're using AngularJS there's no need to use both onclick and ng-click .
  2. If you want to show all products from your list you may want to use ng-repeat .
  3. You need to initialize your Module for your AngularJS controller to load, and the controller must be within the module in the HTML code.

I've done an example bellow based on your code, it might help if you edit your answer and add your complete code.

 var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.count = 0; $scope.selectedIndex = 0; $scope.editProductDetail = function (index) { $scope.selectedIndex = index; }; $scope.productList = [ { name: 'Product 1', price: '1,00 U$' }, { name: 'Product 2', price: '2,00 U$' }, { name: 'Product 3', price: '3,00 U$' } ]; }); 
 .selected-item { display: block; color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp" ng-controller="myCtrl" > <h2>Selected Item Number: {{ selectedIndex + 1}}</h2> <!-- I've added +1 since index starts at 0 --> <div ng-repeat="item in productList"> <a href="#" ng-click="editProductDetail($index)" ng-class="{ 'selected-item': $index == selectedIndex }">{{ item.name}} {{item.price}} </a> </div> </div> 

As debabrata was saying you don't need to use both, just use something like this:

// Your controller
$scope.editProductDetail = function(productObject) {
    $scope.setDisplayBlock = true;
    $scope.getProduct  = productObject;
}

// Your HTML
<a href="#" ng-click="editProductDetail(list)" target="_self"></a>
<span id="editProduct" ng-class="{'css-class-with-display-block': setDisplayBlock}">The element to change</span>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM