如何更改函数中的angularjs元素值?

时间:2017-06-25 12:20:13

标签: javascript angularjs

HTML:

<div data-ng-app="story"  data-ng-init="detail='post a story here'">


<div data-ng-controller="detail_controller">
    <input type="text" name="detail" data-ng-model="detail">
    <h1>{{detail}}</h1>
    <input data-ng-click="submit_detail(detail)" type="submit" name="submit_detail" value="Post detail">


    <!--detail dashboard-->
    <div ng-model = "detail_dashboard" data-ng-show = "detail_dashboard.show">

        <div><h1 data-ng-model = "title" class="title">detail: {{title}}</h1></div>
        <div data-posted-answers></div>
    </div>
</div>

</div>

Angular js

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


function updateArticle(data) {
    console.log('updateArticle called '+data);
  

如何更改此处的值?

    $rootScope.title = 'hidfg';
}

app.controller('detail_controller', function($scope) {


    $scope.detail_dashboard = {
        show : false
    };

    $scope.submit_detail = function($value) {

        $scope.detail_dashboard = {
            show : true
        };

        $scope.title = $value;

        updateArticle($value);

    };



});
  

$ scope和$rootScope在内部使用时会出现此错误   updateArticle功能:

ReferenceError: `$rootScope` is not defined

如何更改控制器内的任何元素值?在jQuery中,只需按名称,id,类和数据属性调用元素。但角度我怎么能这样做?

我也尝试过这种方式:

angular.element('title').text(''something new);

但这给了我jqLite:nosel错误

小提琴:https://jsfiddle.net/hadfgy4r/

2 个答案:

答案 0 :(得分:0)

这是您正在寻找的答案:https://jsfiddle.net/27pawemr/2/

       var app = angular.module("story", []);
     //You can't do this, because you're out of the "Angular consciousness"
      /*function updateDashboard(data) {
          console.log('updateArticle called '+data);
           $rootScope.title = 'hidfg';
       }*/

       app.service("myModifier", ["$rootScope", function($rootScope) {
            this.updateDashboard = function(data) {
               console.log('updateArticle called ' + data);
              $rootScope.title = 'hidfg';
           };
    }]);

     app.controller("detailController", ["$scope", "myModifier", function($scope, myModifier) {
     $scope.detail = "post a story here";

     $scope.detailDashboard = {
        show: false
    };

   $scope.submit_detail = function(value) {
      //There's no need to redeclare $scope.detailDashboard
      $scope.detailDashboard.show = true;

      $scope.title = value;

       myModifier.updateArticle(value);

  };



}]);

HTML中也有错误。 ng模型仅适用于输入!

    

<div><h1 class="title">detail: {{title}}</h1></div>
    <div data-posted-answers></div>
</div>

因此将ng模型放在这里没有任何意义

<div><h1 class="title">detail: {{title}}</h1></div>

答案 1 :(得分:-1)

似乎需要像这样使用scope()和$ apply。但我需要为此包含jquery。如果下面的代码可以在没有jquery的情况下修改,请告诉我。

function updateArticle(data) {
var scope = angular.element($("#pquestion")).scope();
    scope.$apply(function(){

        scope.detail_dashboard= {
            show : true
        };

        scope.title= data;
    });
}