2015-10-15 43 views
-1

这里是jsfiddle
HTML:Angular:如何从指令获取兄弟指令值?

<div ng-app="app"> 
    <div ng-controller="mainController"> 
     {{test}} 
     <form> 
      <username></username> 
      <submit></submit> 
     </form> 
    </div> 
</div> 

和JS:

var app = angular.module("app", []); 
app.controller("mainController", ["$scope", function($scope){ 
    $scope.test = "Greetings!" 
}]) 
.directive("username", function(){ 
    return { 
     restrict: "E", 
     controller: function($scope){ 
      this.value = $scope.username; 
     }, 
     template: "<div>username<input type='text' value='123' ng-model='username' /></div>" 
    }; 
}) 
.directive("submit", function(){ 
    return { 
     restrict: "E", 
     require: "username", 
     link: function(scope, ele, attr, ctrl){ 
      ele.bind("click", function(){ 
       console.log(ctrl.value); 
      }); 
     }, 
     template: "<div><input type='submit' value='submit' /></div>" 
    }; 
}); 

我想,当点击提交按钮,获取用户名的输入值。我做错了什么?
有人能帮助我吗?
干杯!

+0

你检查控制台? “错误:[$ compile:ctreq]找不到指令'submit'所需的控制器'username'!” – Claies

+0

换句话说,在这种情况下,您正在错误地使用'require'选项。 – Claies

+0

是的,这就是为什么我会问如何与兄弟姐妹指令联系。 – nich

回答

0

要求只能搜索本身或者它的父母,范围会更容易,避免使用范围,使用需要控制器和u需要自定义窗体作为指令和两个用户名,并提交需要它的控制器