ng-click事件未在span元素上触发

时间:2016-02-20 06:03:42

标签: angularjs

为什么ng-click在以下代码中不起作用? 应该很简单。我错过了什么 感谢

$name  = 'test & sample';
$postid = 9;
$term = get_term_by('name', apply_filters( 'pre_term_name', $name, 'product_cat'), 'product_cat');
if (is_object($term)) 
{
    wp_set_object_terms($postid, $term->term_id, 'product_cat');
}
(function() {
    'use strict';
    // Set up the app.
    var mainApp = angular.module('mainApp', []);

    // Create a controller.
    mainApp.controller('navController', ['$scope', '$log' ,function($scope, $log) {
        //$scope.firstName= "John";
        //$scope.lastName= "Doe";,
        $scope.openTab = function (tabNumber) {
            $log.log(tabNumber);
        };

        var s =1;
    }]);
}());

3 个答案:

答案 0 :(得分:6)

使用controllerAs时,必须将变量和方法直接绑定到控制器实例this,而不是$scope

// this.firstName = "John";
// this.lastName = "Doe";
this.openTab = function (tabNumber) {
    $log.log(tabNumber);
};

因为controllerAs将控制器实例中的控制器实例this设置为$scope.nc

答案 1 :(得分:2)

您在控制器中使用$scope,但在使用as的视图中。

如果您想严重使用as,那么控制器中的方法应使用this关键字

喜欢这个

this.openTab = function (tabNumber) {
    $log.log(tabNumber);
};

但是如果想要使用控制器范围,那么你的视图应该是

<span ng-click="openTab(1)" class="btn"> tab 1</span>
<span ng-click="openTab(2)" class="btn"> tab 2</span>
<span ng-click="openTab(3)" class="btn"> tab 3</span>

答案 2 :(得分:0)

请试试这个..

    (function() {
    'use strict';
    // Set up the app.
    var mainApp = angular.module('mainApp', []);

    // Create a controller.
    mainApp.controller('navController', ['$scope', '$log' ,function($scope, $log) {
        //$scope.firstName= "John";
        //$scope.lastName= "Doe";,
        $scope.openTab = function (tabNumber) {
            $log.log(tabNumber);
        };

        var s =1;
    }]);
    }());


<!DOCTYPE html>
<html>
    <head>
        <script src="/js/angular.js"></script>
        <script src="/js/app/app.js"></script>

        <link rel="stylesheet" href="/css/styles.css" />

    </head>
    <body ng-app="mainApp">
        <div class="navigation" ng-controller="navController">
            <!--<p>Name: <input type="text" ng-model="name"></p>
            <p ng-bind="name"></p>
            <p>{{name}}</p>
            -->
            <span ng-click="openTab(1)" class="btn"> tab 1</span>
            <span ng-click="openTab(2)" class="btn"> tab 2</span>
            <span ng-click="openTab(3)" class="btn"> tab 3</span>
        </div>
    </body>
</html>