Angularjs 使用ng init初始化作用域在指令中没有绑定

Angularjs 使用ng init初始化作用域在指令中没有绑定,angularjs,angularjs-directive,angularjs-scope,Angularjs,Angularjs Directive,Angularjs Scope,您好,我正在尝试使用ng init事件中定义的“@”将值绑定到指令。但这不在我的指令中,它返回undefined。这个属性什么时候真正解析它在编译、链接中?还有,为什么它总是返回未定义?我做错了什么 <!DOCTYPE html> <html ng-app="app"> <head> <script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://cod

您好,我正在尝试使用ng init事件中定义的“@”将值绑定到指令。但这不在我的指令中,它返回undefined。这个属性什么时候真正解析它在编译、链接中?还有,为什么它总是返回未定义?我做错了什么

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
    <script src="script.js"></script>
  </head>

  <body ng-controller="demoController" ng-init="init()">
    <h1>Confused directives!!!</h1>
    <my-user userName="{{user.name}}"></my-user>
    <br>
    {{user.name}}
  </body>

</html>

(function(){
    'use strict';
    var app = angular.module('app', []);


    app.controller('demoController', ['$scope', demoController])

    function demoController($scope){
        console.log('Im in the controller');
        $scope.init = function (){
            $scope.user = {
                name: 'Argo'
            }
            console.log('Im in init method of controller')
        }
    }

    app.directive('myUser', myUser);

    function myUser(){
        return {
            restrict: 'AE',
            replace: true,
            scope: {
                userName: '@'
            },
            template: '<div><b>{{userName}} is defined from init method </b></div>',
            link: function(scope, ele, attr){
                console.log('Im in link method of directive');
                console.log('this is loaded' + scope.userName);
                attr.$observe('userName', function(newValue){
                    console.log(newValue);
                })
            }
        }
    }
})();
http://plnkr.co/edit/vAKMNub8HRcphiaMMauR?p=preview

混乱的指令!!!

{{user.name} (功能(){ "严格使用",; var-app=angular.module('app',[]); app.controller('demoController',['$scope',demoController]) 功能控制器($scope){ log(“控制器中的Im”); $scope.init=函数(){ $scope.user={ 名称:“Argo” } log('controller的init方法中的Im') } } 应用程序指令(“我的用户”,我的用户); 函数myUser(){ 返回{ 限制:“AE”, 替换:正确, 范围:{ 用户名:'@' }, 模板:{{userName}}是从init方法中定义的, 链接:功能(范围、元素、属性){ log('Im in link method of directive'); console.log('已加载'+scope.userName); 属性$observe('userName',函数(newValue){ console.log(newValue); }) } } } })(); http://plnkr.co/edit/vAKMNub8HRcphiaMMauR?p=preview
您可以设置一个plunker吗?您应该使用属性名
用户名
,而不是像在HTML中那样使用
用户名
。此外,官方文件规定,
ng init
仅应在需要别名的特殊情况下使用,因此请在控制器中调用初始化函数。