Angularjs:ng-click在指令中不起作用

时间:2015-08-02 08:09:02

标签: angularjs angularjs-directive angularjs-ng-click

我正在构建一个树视图,每个分支都在一个指令中创建。 问题是事件ng-click不起作用。 这是指令,事件在var myBranch的末尾。 它调用的函数位于指令“shapetree”元素所属的控制器内。无论如何,一个简单的警报在ng-click事件中也不起作用。 你能帮帮我吗?

app.directive("shapetree", function() {
	 return {
		restrict: "A",
		link: function($scope, elem, attrs) {
			
			$scope.$watch(
				function($scope) {
					return $scope.courseCats
				},
				function() {
					...
					var myBranch = angular.element('<li >'+courseCat+'&nbsp;<span role="button" ng-click="addObl('+idAnagSel+','+idCourseCat+')"></span></li>');
					
					var mainTree = angular.element('#mainTree');
					
					mainTree.append(myBranch);
					
				}
			);
		}
	 }
});

2 个答案:

答案 0 :(得分:1)

您的指示应该是这样的:

app.directive("shapetree", function () {
    return {
        restrict: 'A',
        template: '<li>{{courseCat}}&nbsp;<span role="button" ng-click="addObl(idAnagSel, idCourseCat)"></span></li>',
        link: function ($scope, elem, attrs) {
            // Just an example to assign the right variables
            $scope.idAnagSel = 'x';
            $scope.idCourseCat = 'y';
            $scope.courseCats = 'z';
            $scope.addObl = function (idAnagSel, idCourseCat) {
                 // Do something
            };
        }
    }
});

答案 1 :(得分:0)

&#13;
&#13;
app.directive("shapetree", function($compile) {
	 return {
		restrict: "A",
		link: function($scope, elem, attrs) {
			
			$scope.$watch(
				function($scope) {
					return $scope.courseCats
				},
				function() {
					...
					var myBranch = angular.element('<li >'+courseCat+'&nbsp;<span role="button" ng-click="addObl('+idAnagSel+','+idCourseCat+')"></span></li>');
					
					var mainTree = angular.element('#mainTree');
					
compiled = $compile(myBranch);

					mainTree.append(myBranch);
					
compiled($scope);
				}
			);
		}
	 }
});
&#13;
&#13;
&#13;