Home  >  Q&A  >  body text

angular.js - angular中ng-init中定义值在控制器里面获取不到值

  1. 我的问题:
    如题: angular中ng-init中定义值在控制器里面获取不到值

  2. 相关代码:

<p class="container" ng-app="app" ng-controller="ctrl" ng-init="demo='风一样的男子'">
    <h1>ng-init</h1>
    <input ng-model="demo" type="text">
    demo = {{demo}}

    <button type="button" ng-click="demoClick()">button</button>
</p>
(function(angular) {
    'use strict';
    var app = angular.module('app', []).controller('ctrl', ctrl);

    function ctrl ($scope, $http) {
        console.log('直接获取: ' + $scope.demo); // undefined

        $http.post('/demo', {
            direction: $scope.demo // undefined
        });

        $scope.demoClick = function () {
            console.log('click: ' + $scope.demo); // 风一样的男子

            $http.post('/demo', {
            direction: $scope.demo // 风一样的男子
        });
        };
    }
}(angular));

WHY?

为情所困为情所困2738 days ago572

reply all(3)I'll reply

  • 世界只因有你

    世界只因有你2017-05-15 17:07:49

    This involves the compilation and linking process of each instruction. It should be noted that on the same node, if there is an ngController instruction, it will execute the compilation process before any other instructions (its priority is 500, while ngInit's priority is 450). Therefore, when executing the link function of ngController, which is the controller function we often see, ngInit has not completed the compilation process, so it naturally cannot obtain the value of demo.

    http://stackoverflow.com/ques...

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-15 17:07:49

    The console has not been init yet, try the console in watch

    reply
    0
  • PHP中文网

    PHP中文网2017-05-15 17:07:49

    If you want to access the demo at the location above. I think it should be used. $rootscope.demo or $parentscope.demo

    The above problem should be a scope problem.

    reply
    0
  • Cancelreply