angular.js - angular中ng-init中定义值在控制器里面获取不到值
为情所困
为情所困 2017-05-15 17:05:49
0
3
531
  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?

为情所困
为情所困

reply all(3)
世界只因有你

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...

过去多啦不再A梦

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

Ty80

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!