我的SPA具有以下代码

<ul id = "vers"> <span>My App</span>
    <li class="sub">
        <a href="#">Version</a>
        <ul>
            <li class="sub">
                <a href="#">V2</a>
                <ul ng-controller="V2Ctrl">
                    <li ng-repeat = "v2 in V2s"><a href="#">{{v2}}</a></li>
                </ul>
            </li>
            <li class="sub">
                <a href="#">V3</a>
                <ul ng-controller="V3Ctrl">
                    <li ng-repeat = "v3 in V3s"><a href="#">{{v3}}</a></li>
                </ul>
            </li>
        </ul>
    </li>
</ul>


我想将选定的值放入<span>中进行显示,并将该值存储到应用程序范围的变量中,以便将该值用作其他内容的输入。

我该如何在AngualrJs中做到这一点?

更新:

我正在寻找类似于以下内容的效果:

var vers = "";
var link = document.getElementById("vers");
AttachEvent(link, "click", EventHandler);

function AttachEvent(element, type, handler) {
    if (element.addEventListener) element.addEventListener(type, handler, false);
    else element.attachEvent("on"+type, handler);
}

function EventHandler(e) {
    alert(e.target.innerHTML);
  vers = e.target.innerHTML;
}


上面的代码实际上在顶级列表中没有控制器的情况下也有效。
那么我需要一个控制器吗?如果是,则何时调用控制器?

希望这使我的问题更清楚。

最佳答案

这是你想要的?

的HTML

<ul ng-app="app" ng-controller="appController"> <span>{{value}}</span>
<li class="sub">
    <a href="#">Version</a>
    <ul>
        <li class="sub">
            <a href="#">V2</a>
            <ul>
                <li ng-repeat = "v2 in fruits"><a href="javascript:void(0)" ng-click="select(v2)">{{v2}}</a></li>
            </ul>
        </li>
        <li class="sub">
            <a href="#">V3</a>
            <ul>
                <li ng-repeat = "v3 in countries"><a href="javascript:void(0)" ng-click="select(v3)">{{v3}}</a></li>
            </ul>
        </li>
    </ul>
</li></ul>


JS

var App = angular.module('app', []);
App.controller('appController', function($scope, fruits, countries){
$scope.value="";
$scope.v2 = 'Apple'
$scope.v3 = 'Windows'
$scope.fruits = fruits;
$scope.countries = countries;

$scope.select = function(val){
  $scope.value = val;
}
});
App.factory('fruits', function(){
  return ['apple', 'banana', 'mango']
});
App.factory('countries', function(){
  return ['Dominican Republic', 'Panama', 'Argentina']
});


Check this example working here...

09-25 18:31