Angularjs使用指令替换选项

时间:2013-06-26 09:14:28

标签: angularjs replace directive

当我将replace属性设置为true时,浏览器崩溃了。 以下是plunker链接:http://plnkr.co/edit/9pXdDGo4ccxljwIo3NN0 有什么问题?

的index.html

    <!doctype html>
<html ng-app="cvApp" ng-cloak>
<head>
  <meta charset="utf-8" />
    <title>
        Mixing Static And Dynamic Options In An AngularJS Select Menu
    </title>
</head>
<body ng-controller="ctrl">
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script type="text/javascript"  src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script>

<script type="text/javascript" src="script.js"></script>


    <div radios selected-option="selectedOption" option-list="optionList" name="ms">
</body>
</html>

radios.html

    <label data-ng-repeat="opt in optionList" class="radio inline">

    <input type="radio" name="{{name}}" ng-model="selectedOption" ng-value="opt" />
    {{opt.name}}
</label>

的script.js

        var cvApp = angular.module('cvApp',[]);

    cvApp.controller('ctrl', function ($scope) {
        $scope.optionList=[{name:"evli",value:1},{name:"bekar",value:2}]
        $scope.selectedOption=$scope.optionList[0];
    });

cvApp.directive("radios", function() {
    return {
        restrict: "A",
        //replace:true,
        templateUrl: 'radios.html',
        scope: {
            selectedOption: "=",
            optionList: "=",
            name:"@"
        }
    };
});

1 个答案:

答案 0 :(得分:2)

您的指令模板将label标记定义为模板的根元素,但您的标签标记也使用ng-repat指令,该指令在执行时会创建多个根元素。在ticket中解决了没有根DOM节点的指令模板问题。

解决方法是将label标记包含在另一个“真正的”根元素中:

<div>
  <label data-ng-repeat="opt in optionList" class="radio inline">
    <input type="radio" name="{{name}}" ng-model="selectedOption" ng-value="opt" />
    {{opt.name}}
  </label>
</div>