如何从angular指令获取数据

use*_*557 7 angularjs angularjs-directive angularjs-scope

我希望有人可以用一个小例子来帮助我,因为棱角分裂让我疯狂:(

我是第一次制作一个应该遵循这个结构的Formular:Angular APP

mainController
----> smallController1
--------> otherElements
----> smallController2
--------> otherElements
----> Directive1(实例1)
----> anotherSmallController
----> Directive1(实例2)

Directive1接收许多属性,每个实例将允许选择许多选项,并且用户交互的结果应该存储在一个对象中,并且该对象应该分别从mainController为每个实例访问.

有没有人有这样的例子?

先谢谢你,约翰

Nee*_*rma 10

从指令获取数据的最佳方法是将模型附加到指令的自我范围.

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

app.controller('mainController', 
                [
  '$scope', 
  function($scope){
    $scope.myObj = "Initial Value";
  }
]);

app.directive('dirName', [
  function(){
    return {
      restrict : 'A',
      scope : {
        obj : "=ngModel"
      },
      link : function(scope, element, attrs){
        scope.obj = attrs.newValue;
      }
    };
  }
]);
Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body ng-app="app" ng-controller="mainController">
  <input dir-name ng-model="myObj" new-value="Final Value">
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

您也可以检查此bin:http://jsbin.com/fuqujo/1/edit?html,js,output