如何根据从下拉列表中选择的选项注入指令模板

时间:2013-11-19 23:50:57

标签: javascript angularjs angularjs-directive

这是我的HTML:

<html ng-app="myApp">
<div id="inputPane" ng-controller="MyInput">
     <select ng-model="dataSource" ng-options="data.Name for data in dataSources">
          <option value="">-- choose a data source --</option>
     </select>
     <div id="dataParameters">
    <my-param></my-param>
     </div>
</div>
</html>

这是脚本:

angular.module("myApp", [])
    .controller("MyInput", function($scope) {
        $scope.dataSources = [
            {
                Name: "Twitter",
                Value: "twitter"
            },
            {
                Name: "Facebook",
                Value: "facebook"
            }
        ]

        $scope.dataSource = $.scope.dataSources[0];
    })
    .directive("myParam", function() {
        //I would like to do this
                if (MyInput.dataSource.Name == "Twitter") {
                     return {
                         restrict: "E",
                         templateUrl: "../views/my-param.html"
                      }
                }
                else {
                   //inject another template
                }
    })

根据所选的数据源,我想显示不同的参数。我是棱角分明的新手,所以不知道如何去做。请帮忙。

1 个答案:

答案 0 :(得分:2)

你不能那样。但您可以做的是动态加载并根据属性添加模板。该代码看起来像

app.directive('myParam', function($compile, $http, $templateCache) {
    // Returns a promise to the template string available at templateUrl
    var getTemplate = function(templateUrl) {
      return $http.get(templateUrl, { cache: $templateCache });
    }

    var linker = function(scope, el, attrs) {

      var obtainEmptyContainer = function() {
        // We don't want to replace element but instead change the content 
        // this is done by adding a container if one doesn't exist yet
        var container = el.children()[0] || el.append("<div></div>");
        $(container).html(""); // clear content
        return $(container).append("<div></div>");
      }

      // When the templateUrl attribute of the directive changes,
      attrs.$observe('templateUrl', function(newVal, oldVal) {
        // get the new template
        var template = getTemplate(newVal);
        // and the container
        var container = obtainEmptyContainer(); 

        template.success(function(html) {
          // set the container to the uncompiled template
          container.html(html);
        }).then(function (response) { 
          // compile (render) and replace the container
          container.replaceWith($compile(container.html())(scope));
        });
      });
    }

    return {
      restrict: 'E',
      scope: {
        templateUrl: '@'
      },
      link: linker
    };
  })

现在您可以将其用作

<my-param template-url="/path/to/some/template.html"></my-param>

当然,您可以将该代码更改为不使用templateUrl,而是将其他内容更改为指令(或控制器)中的值。