本文介绍了传递对象angularjs指令从控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图让我的头AngularJS指令各地。我需要从我的主控制器的指令传递一个完整的对象。见下文和的jsfiddle的code:

Trying to get my head around AngularJS directives. I need to pass a full object from my main controller to the directive. See the code below and jsfiddle: http://jsfiddle.net/graphicsxp/Z5MBf/4/

<body ng-app="myApp">
<div ng-controller="MandatCtrl">
    <div person myPerson="mandat.person"></div>

    <span>{{mandat.rum}}</span>
    <span>{{mandat.person.firstname}}</span>

</div>

和脚本:

var myApp = angular.module("myApp", []);

myApp.controller("MandatCtrl", function ($scope) {
$scope.mandat = { rum: "15000", person: { id: 1408, firstname: "sam" } };
});

myApp.directive("person", function () {     
return {
    scope: {
        myPerson: "="
    },
    template: 'test: <div ng-model="myPerson"><input type="text" ng-model="firstname" /></div>'
}
});

确定,正在罚款mandat.rum和mandat.person.firstname结合。

Ok, the binding is working fine for mandat.rum and mandat.person.firstname.

不过,我试图通过mandat.person的指令,而这是行不通的。我知道我必须做一些错误的,问题是什么? :)

However, I'm trying to pass mandat.person to the directive, and it does not work. I know I must be doing something wrong, the question is what ? :)

推荐答案

请参见下面的工作副本

<!doctype html>
<html ng-app="plunker" >
<head>
  <meta charset="utf-8">
  <title>AngularJS Plunker</title>

  <link rel="stylesheet" href="style.css">
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
  <script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
      <span>{{mandat.rum}}</span>
      <span>{{mandat.person.firstname}}</span>
    <input type="text" ng-model="mandat.person.firstname" />
    <my-directive mandateperson="mandat.person" >

      </my-directive>
    <script type="text/javascript">
        var app = angular.module('plunker', []);

        app.controller('MainCtrl', function ($scope) {
            $scope.mandat = { name: "John", surname: "Doe", person: { id: 1408, firstname: "sam" } };
        });


        app.directive('myDirective', function () {
            return {
                restrict: 'E',
                template: "<div><span>{{mandateperson.id}}<span><input type='text' ng-model='mandateperson.firstname' /></div>",
                replace: true,
                scope: { mandateperson: '=' }
                }
            }
        )
    </script>
</body>
</html>

这篇关于传递对象angularjs指令从控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 22:06